简体   繁体   English

如何使用熊猫将用户定义的列名称写入CSV文件?

[英]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? 将透视表写入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')

I tried to use the header parameter: 我尝试使用header参数:

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 : 解决方法:在调用to_csv之前更改ptable的列:

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 实际上,它应该通过传递header参数的列表来工作,但不确定为什么,这可能是一个错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM