Skip to content Skip to sidebar Skip to footer

How To Create Pandas Dataframe With Index From The List Of Tuples

What would be the best way to create pandas DataFrame with index from records. Here is my sample: sales = [('Jones LLC', 150, 200, 50), ('Alpha Co', 200, 210, 90), ('Blue

Solution 1:

Simpliest is set_index:

df = pd.DataFrame.from_records(sales, columns=labels).set_index('account')
print (df)
           Jan  Feb  Mar
account                 
Jones LLC  150  200   50
Alpha Co   200  210   90
Blue Inc   140  215   95

Or select by list comprehensions:

labels = [ 'Jan', 'Feb', 'Mar']
idx = [x[0] for x in sales]
data = [x[1:] for x in sales]

df = pd.DataFrame.from_records(data, columns=labels, index=idx)
print (df)
           Jan  Feb  Mar
Jones LLC  150  200   50
Alpha Co   200  210   90
Blue Inc   140  215   95

Post a Comment for "How To Create Pandas Dataframe With Index From The List Of Tuples"