Renaming multi index in pandas

Viewed 75

Is there a way to rename an index in a multi-index data frame?

Example

import pandas as pd


df = pd.DataFrame([
['green','M', 10.1, 'class2'],
['red', 'L', 13.5, 'class1']])
df.columns = ['color', 'size', 'price', 'classifier']

df.set_index(['color','size'], inplace=True)

Gives

            price   classifier
color   size

green   M   10.1    class2
red     L   13.5    class1

I want to rename the index 'size' to become size_modified

df.rename(index={'size': 'Size_Mod'}, inplace=True) 

didn't work

2 Answers

you need df.rename_axis instead of df.rename:

df = df.rename_axis(index={'size': 'Size_Mod'}) 

print(df)

                price classifier
color Size_Mod                  
green M          10.1     class2
red   L          13.5     class1

Another way, make sure the order of the names is correct. But it has a smaller fingerprint!

df.index.names = ['color','Size_Mod']
Related