create pandas dataframe from list of tuples

Viewed 5530

I've seen a couple of similar threads but they didn't really help me hence the new post.

I would like to create the df below from a list of tuples:

Values         Total  extra
label                      
Pictionary  0.000000     12
Chess       4.609929     12
Cluedo      8.421986     12

Here are all the components to make it happen:

columns = ['Total, 'extra']

tups = [(u'Pictionary', 0.0, 12)
        (u'Chess', 4.6099290780141837, 12)
        (u'Cluedo', 8.4219858156028362, 12)]

My failed attempt:

pd.DataFrame(tups, columns=columns)

Error message:

AssertionError: 2 columns passed, passed data had 3 columns
2 Answers

You can use pandas.DataFrame.from_records()

import pandas as pd

data = [(1,2,3),
        (4,5,6),
        (7,8,9)]

col_names = ['Col0', 'Col1', 'Col2']
row_names = ['Row0', 'Row1', 'Row2']

df = pd.DataFrame.from_records(data, columns=col_names, index=row_names)

print(df)

      Col0  Col1  Col2
Row0     1     2     3
Row1     4     5     6
Row2     7     8     9
Related