且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重命名Pandas中的MultiIndex列

更新时间:2023-12-01 09:04:16

使用 set_levels :

In [22]:
df.columns.set_levels(['b1','c1','f1'],level=1,inplace=True)
df

Out[22]:
     a         d
    b1   c1   f1
0    1    2    3
1   10   20   30
2  100  200  300

rename 设置名称对于索引,它不会重命名列名称:

rename sets the name for the index, it doesn't rename the column names:

In [26]:
df.columns = df.columns.rename("b1", level=1)
df

Out[26]:
      a         d
b1    b    c    f
0     1    2    3
1    10   20   30
2   100  200  300

这就是为什么您会收到错误消息

This is why you get the error