You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas多级索引DataFrame重命名索引无效?问题排查

Pandas多级索引重命名无效的问题排查与解决

问题场景

我有一个带两级索引的Pandas DataFrame(result_df),执行print(result_df)输出如下:

a_column  ...        another_column
datetime_end_format datetime_end_format                       ...                      
1                   2023                                1159  ...                  1027
2                   2023                                2765  ...                  2466
3                   2023                                2493  ...                  2303
4                   2023                                3016  ...                  2860
5                   2023                                4174  ...                  4036
6                   2023                                3916  ...                  3870
7                   2023                                 539  ...                   542

该DataFrame的两级索引名称均为datetime_end_format,执行print(result_df.index)输出:

MultiIndex([(1, 2023),
        (2, 2023),
        (3, 2023),
        (4, 2023),
        (5, 2023),
        (6, 2023),
        (7, 2023)],
       names=['datetime_end_format', 'datetime_end_format'])

尝试用result_df.index.rename(['month','year'])重命名索引,但索引名称没有变化,再次打印索引还是原名称。


错误原因

pandas.Index.rename()方法默认返回一个修改后的新索引对象,不会直接修改原DataFrame的索引。你只调用了方法但没有将返回值赋值给原索引,所以原索引完全没变化。

正确解决方法

有两种方式可以实现索引重命名:

  1. 将返回的新索引赋值给原DataFrame的索引:
result_df.index = result_df.index.rename(['month', 'year'])
  1. 使用inplace=True参数直接修改原索引:
result_df.index.rename(['month', 'year'], inplace=True)

执行任意一种方式后,再打印result_df.index,就能看到索引名称已经更新为['month', 'year']了。

内容的提问来源于stack exchange,提问作者acolls_badger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 17:07:01