2014-02-06 49 views
2

將數據透視表寫入csv文件時,是否可以編寫自己的列名?如何使用熊貓將用戶定義的列名寫入csv文件?

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') 

我試圖用header參數:

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

但列名沒有改變...

回答

2

這裏是一個變通:前更改ptable列致電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') 
1

只需在寫之前重新命名:

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

應該在傳遞的列表中header參數事實的工​​作,不知道爲什麼,可能是一個錯誤