7

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 Inc', 140, 215, 95)]
labels = ['account', 'Jan', 'Feb', 'Mar']
df = pd.DataFrame.from_records(sales, columns=labels)

I need 'Account' to be an index here (not a column) Thanks

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.