pandas 重命名熊猫数据框的列名没有按预期工作 - python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47060980/
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
Renaming the column names of pandas dataframe is not working as expected - python
提问by Arvinth Kumar
I am having below pandas dataframe df
. I am trying to rename the column names but it not working as expected.
我有以下Pandas数据框df
。我正在尝试重命名列名,但它没有按预期工作。
Code:
代码:
mapping = {df.columns[0]:'Date', df.columns[1]: 'A', df.columns[2]:'B', df.columns[3]: 'C',df.columns[4]:'D', df.columns[5]: 'E',df.columns[6]:'F', df.columns[7]: 'G',df.columns[8]:'H', df.columns[9]: 'J'}
df.rename(columns=mapping)
Output of df.columns
:
的输出df.columns
:
MultiIndex(levels=[['A Index', 'B Index', 'C Index', 'D Index', 'E Index', 'F Index', 'G Index', 'H Index', 'I Index', 'J Index', 'K Index', 'L Index', 'M Index', 'N Index', 'O Index', 'date', 'index'], ['PX_LAST', '']],
labels=[[16, 15, 11, 9, 10, 6, 3, 4, 2, 5, 14, 1, 13, 12, 7, 0, 8], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
names=['ticker', 'field'])
Even after running the code, column name stays the same. Can anyone help rename column names of this dataframe.
即使在运行代码之后,列名也保持不变。任何人都可以帮助重命名此数据框的列名。
回答by johnchase
Because you know the order of the columns already why not just use:
因为您已经知道列的顺序,所以为什么不直接使用:
df.columns = ['Date', 'a', 'b', 'c', 'd', 'e', 'f' 'g', 'h', 'i', 'j']
Otherwise if you want to use rename
you will need to assign it to a variable:
否则,如果要使用rename
,则需要将其分配给变量:
mapping = {df.columns[0]:'Date', df.columns[1]: 'A', df.columns[2]:'B', df.columns[3]: 'C',df.columns[4]:'D', df.columns[5]: 'E',df.columns[6]:'F', df.columns[7]: 'G',df.columns[8]:'H', df.columns[9]: 'J'}
df = df.rename(columns=mapping)