Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

csv

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...

like image 627
HappyPy Avatar asked Dec 21 '25 13:12

HappyPy


2 Answers

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')
like image 149
unutbu Avatar answered Dec 24 '25 02:12

unutbu


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

like image 37
EdChum Avatar answered Dec 24 '25 02:12

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!