简体   繁体   中英

Is there a more efficient way to write a dataframe (columns and data) to list?

I haven't found a function to write a dataframe with columns and data to a list. I feel like there must be a function for this, but I can't find it so instead I concatenate together.

import pandas as pd
df = pd.DataFrame(data = [['Project1', 'CT', 800], ['Project2', 'MA', 1000], ['Project3', 'CA', 20]], columns=['Project ID', 'State', 'Cost'])

print [df.columns.tolist()] + df.values.tolist()

Desired output:

[['Project ID', 'State', 'Cost'], ['Project1', 'CT', 800L], ['Project2', 'MA', 1000L], ['Project3', 'CA', 20L]]

Maybe use transpose operator to do the trick?

df.T.reset_index().values.T.tolist()

[['Project ID', 'State', 'Cost'],
 ['Project1', 'CT', 800],
 ['Project2', 'MA', 1000],
 ['Project3', 'CA', 20]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM