将pandas数据框保存到csv时,如何保留columns.name? [英] When saving a pandas dataframe to csv how do I retain the columns.name?
本文介绍了将pandas数据框保存到csv时,如何保留columns.name?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在ipython中运行以下命令
When I run the following in 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"将被删除:
However when I open output.csv
the "y" is removed:
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
?
How do I make it so that the df.columns.name
is retained when I output the dataframe to csv?
目前的粗略解决方法是我正在执行以下操作:
Current crude work-around is me doing the following:
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
有什么更好的了!感谢您的帮助(提前).
Something better would be great! Thanks for your help (in advance).
这就是我正在研究的内容: https://github.com/SimonBiggs/Electron-抠图因子
This is what I am working on: https://github.com/SimonBiggs/Electron-Cutout-Factors
查看全文