简体   繁体   中英

how to write user-defined column names to a csv file using pandas?

Is is possible to write my own column names when writing a pivot table to a csv file?

import pandas as pd

c1 = ['a','a','a','a','b','b','b','b']
c2 = ['x','x','y','y','x','x','y','y']
c3 = [1, 2, 1, 2, 1, 2, 1, 2]
val = [85, 47, 29, 93, 15, 21, 65, 16]

df = pd.DataFrame({'c1':c1, 'c2':c2, 'c3':c3, 'val':val})

ptable = pd.pivot_table(data=df, cols=['c2','c3'], rows='c1')

I tried to use the header parameter:

ptable.to_csv('test.csv', header=['n1','n2','n3','n4'])

but the column names weren't changed...

Here is a work-around: Change the columns of ptable before calling to_csv :

ptable = pd.pivot_table(data=df, cols=['c2','c3'], rows='c1')
ptable.columns = ['n1','n2','n3','n4']
ptable.to_csv('/tmp/test.csv')

Just rename before writing:

ptable.columns=['n1','n2','n3','n4']
ptable.to_csv(r'c:\data\test.csv')

It should in fact work passing the list for the header parameter, not sure why, could be a bug

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