如何(重)命名 pandas 数据框中的空列标题而不导出到CSV [英] How to (re)name an empty column header in a pandas dataframe without exporting to csv
问题描述
我有一个带有索引列和一系列未命名值的熊猫数据框df1
.我想给未命名系列指定一个名称.
I have a pandas dataframe df1
with an index column and an unnamed series of values. I want to assign a name to the unnamed series.
到目前为止,我知道的唯一方法是使用以下命令导出到df1.csv
:
The only way to do this that I know so far is to export to df1.csv
using:
df1.to_csv("df1.csv", header = ["Signal"])
,然后使用:
pd.read_csv("df1.csv", sep=",")
但是,这会浪费时间和存储空间.如何在内存中执行此操作?
However, this costs time and storage space. How to do this in-memory?
当我做df2 = df1.rename(columns = {"" : "Signal"}, inplace = True)
我屈服:
AttributeError: "Series" object has no attribute "Signal"
.
推荐答案
我认为必须删除inplace=True
,因为它返回None
:
I think inplace=True
has to be removed, because it return None
:
df2 = df1.rename(columns = {"" : "Signal"})
df1.rename(columns = {"" : "Signal"}, inplace = True)
另一种解决方案是按位置分配新名称:
Another solution is asign new name by position:
df.columns.values[0] = 'Signal'
示例:
df1 = pd.DataFrame({'':[1,2,3],
'B':[4,5,6],
'C':[7,8,9]})
print (df1)
B C
0 1 4 7
1 2 5 8
2 3 6 9
df2 = df1.rename(columns = {"" : "Signal"})
print (df2)
Signal B C
0 1 4 7
1 2 5 8
2 3 6 9
这篇关于如何(重)命名 pandas 数据框中的空列标题而不导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!