重命名 pandas 数据框的列名未按预期工作-python [英] Renaming the column names of pandas dataframe is not working as expected - python
本文介绍了重命名 pandas 数据框的列名未按预期工作-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下熊猫数据框df
.我正在尝试重命名列名,但没有按预期工作.
I am having below pandas dataframe df
. I am trying to rename the column names but it not working as expected.
代码:
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'])
即使在运行代码后,列名保持不变.任何人都可以帮助重命名此数据框的列名.
Even after running the code, column name stays the same. Can anyone help rename column names of this dataframe.
推荐答案
因为你已经知道列的顺序为什么不直接使用:
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']
否则如果你想使用 rename
你需要将它分配给一个变量:
Otherwise if you want to use rename
you will need to assign it to a variable:
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)
这篇关于重命名 pandas 数据框的列名未按预期工作-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文