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

六月ゝ 毕业季﹏ 提交于 2019-12-10 18:18:10

问题


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.

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"])

and then re-import using:

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)

I yield:

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


回答1:


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'

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


来源:https://stackoverflow.com/questions/41096611/how-to-rename-an-empty-column-header-in-a-pandas-dataframe-without-exporting-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!