Skip to main content
 首页 » 编程设计

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

2025年05月04日10luoye11

我有下面的 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']) 

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

请您参考如下方法:

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

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

否则,如果您想使用重命名,您需要将其分配给一个变量:

 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)