简体   繁体   中英

specify a first column when exporting csv using pandas

Wondering how to specify a first column using pandas?

For example, I have a dataframe df with variables var1, var2, var3,...varx , I would like the first column to be var3 in the csv generated.

df.to_csv('location/export.csv', index=False)

You can rearrange the columns in any way you want by doing

df[['var3', 'var1', 'var2', ..., 'varx']].to_csv('location/export.csv', index=False)

If you just want to have var3 in the beginning, there's a less manual way in

cols = df.columns.tolist()
cols.remove('var3')
df[['var3'] + cols].to_csv('location/export.csv', index=False)

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