重命名 pandas 数据框的列未按预期工作

问题描述 投票:0回答:3

我有下面的 pandas 数据框

df
。我正在尝试重命名列名称,但它没有按预期工作。

代码:

 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) 

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

即使运行代码后,列名称也保持不变。任何人都可以帮助重命名此数据框的列名称。

python pandas dataframe multiple-columns
3个回答
37
投票

因为你已经知道列的顺序为什么不直接使用:

df.columns = ['Date', 'a', 'b', 'c', 'd', 'e', 'f' 'g', 'h', 'i', 'j']

否则,如果您想使用

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)

10
投票

假设您有一个映射,例如:

mapping = {"old_name_1" : "new_name_1", "old_name_2" : "new_name_2"}

熊猫版< 1.4.3

鉴于 pandas 之前的文档,axis 参数的默认值为 0(表示索引)。

因此,将命令更改为:

df = df.rename(columns = mapping, axis = 1)

,其中轴等于 1 表示列,将按预期工作。

此外,您可以使用 inplace 参数,这样您就不必重新设置 DataFrame。

df.rename(columns = mapping, axis = 1, inplace = True)

Pandas 版本 >= 1.4.3

(感谢@Gordon 的提醒)

您可以使用:

df = df.rename(columns = mapping)

df.rename(columns = mapping, inplace = True)

通过新的更新(参见文档),pandas 明白,当您设置映射到列参数时,您意味着更改列的值(因为这是合乎逻辑的);因此,axis 参数是不必要的。


5
投票

inplace=True
添加到
rename
通话中即可。

但是,如果我不指定

inplace=True
,我不确定结果是什么,因为我没有看到任何变化。

© www.soinside.com 2019 - 2024. All rights reserved.