将 Pandas 数据框保存到 csv 时如何保留 columns.name?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25151443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When saving a pandas dataframe to csv how do I retain the columns.name?
提问by SimonBiggs
Initial Problem
初始问题
When I run the following in ipython
当我在 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
it outputs the following result:
它输出以下结果:
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
However when I open output.csvthe "y" is removed:
但是,当我打开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
How do I make it so that the df.columns.nameis retained when I output the dataframe to csv?
df.columns.name当我将数据帧输出到 csv 时,我该如何做到这一点?
Crude workaround
粗略的解决方法
Current crude work-around is me doing the following:
当前的粗略解决方法是我执行以下操作:
df.to_csv('output.csv', index_label = 'x|y')
Which results in output.csvreading:
这导致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
Something better would be great! Thanks for your help (in advance).
更好的东西会很棒!感谢您的帮助(提前)。
Context
语境
This is what I am working on: https://github.com/SimonBiggs/Electron-Cutout-Factors
这就是我正在做的:https: //github.com/SimonBiggs/Electron-Cutout-Factors
This is an example table: https://github.com/SimonBiggs/Electron-Cutout-Factors/blob/master/output/20140807_173714/06app06eng/interpolation-table.csv
这是一个示例表:https: //github.com/SimonBiggs/Electron-Cutout-Factors/blob/master/output/20140807_173714/06app06eng/interpolation-table.csv
回答by WaveRider
You can pass a list to name the columns, then you can specify the index name when you are writing to csv:
您可以传递一个列表来命名列,然后您可以在写入 csv 时指定索引名称:
df.columns = ['column_name1', 'column_name2', 'column_name3']
df.to_csv('/path/to/file.csv', index_label='Index_name')
回答by John Zwinck
How about this? It's slightly different but hopefully usable, since it fits the CSV paradigm:
这个怎么样?它略有不同,但希望可用,因为它符合 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

