3

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

2 Answers 2

3

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')
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.