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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With