重命名pandas dataframe的列名没有按预期工作-python

2024-04-27 19:53:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有熊猫下面的数据帧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'])

即使在运行代码之后,列名也保持不变。有人能帮我重命名这个数据框的列名吗。


Tags: columns数据代码dfdateindexmapping重命名
1条回答
网友
1楼 · 发布于 2024-04-27 19:53:35

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

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)

相关问题 更多 >