简体   繁体   English

重命名多索引索引列名称Python

[英]Rename Multi - Index Column name Python

I have a MultiIndex Dataframe df like Below 我有一个像下面的MultiIndex Dataframe df

                 Office
 Office    
 x         True   2
 y         False  3
 z         True   5

If i reset df.reset_index() it will Error as 如果我重置df.reset_index()它将错误为

"cannot insert Office, already exists"

How its posible to rename the the higher(which comes in very first line) index name "Office" to "Office1" 如何将较高(第一行出现)的索引名“ Office”重命名为“ Office1”

You can use rename_axis or set index.names for rename index names in MultiIndex and rename for change column name: 您可以使用rename_axis或设置index.names来在MultiIndex重命名索引名,并为更改列名rename

#if only rename get Unnamed column
df1 = df.rename(columns={'Office':'another col'}).reset_index()
print (df1)
  Office  Unnamed: 1  another col
0      x        True            2
1      y       False            3
2      z        True            5

df2 = df.rename_axis(('Office', 'bool')).rename(columns={'Office':'Office2'}).reset_index()
print (df2)
  Office   bool  Office2
0      x   True        2
1      y  False        3
2      z   True        5

df.index.names = ('Office1','bool')
df3 = df.rename(columns={'Office':'Office2'}).reset_index()
print (df3)
  Office1   bool  Office2
0       x   True        2
1       y  False        3
2       z   True        5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM