Shivpe_R
Shivpe_R

Reputation: 1080

Rename Multi - Index Column name Python

I have a MultiIndex Dataframe df like Below

                 Office
 Office    
 x         True   2
 y         False  3
 z         True   5

If i reset df.reset_index() it will Error as

"cannot insert Office, already exists"

How its posible to rename the the higher(which comes in very first line) index name "Office" to "Office1"

Upvotes: 2

Views: 1763

Answers (1)

jezrael
jezrael

Reputation: 862481

You can use rename_axis or set index.names for rename index names in MultiIndex and rename for change column name:

#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

Upvotes: 4

Related Questions