如何(重新)命名 Pandas 数据框中的空列标题而不导出到 csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41096611/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:36:16  来源:igfitidea点击:

How to (re)name an empty column header in a pandas dataframe without exporting to csv

pythoncsvpandasrename

提问by sudonym

I have a pandas dataframe df1with an index column and an unnamed series of values. I want to assign a name to the unnamed series.

我有一个df1带有索引列和一系列未命名值的Pandas数据框。我想为未命名系列指定一个名称。

The only way to do this that I know so far is to export to df1.csvusing:

到目前为止,我知道的唯一方法是导出到df1.csv使用:

df1.to_csv("df1.csv", header = ["Signal"])

df1.to_csv("df1.csv", header = ["Signal"])

and then re-import using:

然后使用以下方法重新导入:

pd.read_csv("df1.csv", sep=",")

pd.read_csv("df1.csv", sep=",")

However, this costs time and storage space. How to do this in-memory?

但是,这会花费时间和存储空间。如何在内存中做到这一点?

When I do df2 = df1.rename(columns = {"" : "Signal"}, inplace = True)

当我做 df2 = df1.rename(columns = {"" : "Signal"}, inplace = True)

I yield:

我屈服:

AttributeError: "Series" object has no attribute "Signal".

AttributeError: "Series" object has no attribute "Signal".

回答by jezrael

I think inplace=Truehas to be removed, because it return None:

我认为inplace=True必须删除,因为它返回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'

Sample:

样本:

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