将pandas数据框保存到csv时,如何保留columns.name? [英] When saving a pandas dataframe to csv how do I retain the columns.name?

查看:117
本文介绍了将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

这是一个示例表:推荐答案

您可以传递一个列表来命名列,然后在编写csv时可以指定索引名称:

You can pass a list to name the columns, then you can specify the index name when you are writing to csv:

df.columns = ['column_name1', 'column_name2', 'column_name3']
df.to_csv('/path/to/file.csv', index_label='Index_name')

这篇关于将pandas数据框保存到csv时,如何保留columns.name?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆