如何在保存pandas数据框为csv时保留列名?
初始问题
当我在ipython中运行以下代码时:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.round(9*np.random.rand(4,4), decimals=1))
df.index.name = 'x'
df.columns.name = 'y'
df.to_csv('output.csv')
df
它输出了以下结果:
y 0 1 2 3
x
0 7.6 7.4 0.3 7.5
1 5.6 0.0 1.5 5.9
2 7.1 2.1 0.0 0.9
3 3.7 6.6 3.3 8.4
但是当我打开 output.csv
文件时,"y" 被去掉了:
x 0 1 2 3
0 7.6 7.4 0.3 7.5
1 5.6 0 1.5 5.9
2 7.1 2.1 0 0.9
3 3.7 6.6 3.3 8.4
我该怎么做才能在把数据框输出到csv时保留 df.columns.name
呢?
粗略的解决方法
df.to_csv('output.csv', index_label = 'x|y')
这导致 output.csv
文件的内容变成:
x|y 0 1 2 3
0 7.6 7.4 0.3 7.5
1 5.6 0 1.5 5.9
2 7.1 2.1 0 0.9
3 3.7 6.6 3.3 8.4
如果能有更好的方法就太好了!提前感谢你的帮助。
背景信息
这是我正在做的项目: https://github.com/SimonBiggs/Electron-Cutout-Factors
3 个回答
0
出于某种原因,当列标签是多重索引时,一切都运行得很好。这似乎是pandas库的问题。一个有效且不太复杂的解决方案是:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.round(9*np.random.rand(4,4), decimals=1))
df.index.name = 'x'
df.columns.name = 'y'
##### Add this line to create another column index level
df.columns = [df.columns, df.columns]
df.to_csv('output.csv')
##### When you read it in, specify that the first two lines are both headers
df2 = pd.read_csv('output.csv', index_col=0, header=[0,1])
##### Drop the extra level
df2.columns = df2.columns.droplevel(0)
df2
1
这样怎么样?虽然有点不同,但希望能用得上,因为它符合CSV的格式:
>>> df.columns = ['y{}'.format(name) for name in df.columns]
>>> df.to_csv('output.csv')
>>> print open('output.csv').read()
x,y0,y1,y2,y3
0,3.5,1.5,1.6,0.3
1,7.0,4.7,6.5,5.2
2,6.6,7.6,3.2,5.5
3,4.0,2.8,7.1,7.8
10
你可以传递一个列表来命名列,然后在写入csv文件时可以指定索引的名称:
df.columns = ['column_name1', 'column_name2', 'column_name3']
df.to_csv('/path/to/file.csv', index_label='Index_name')