Home > Software engineering >  Pandas set index name for single level
Pandas set index name for single level

Time:01-23

I would like to set the name for a single level of a pandas dataframe with some chaining method. Consider, e.g., the dataframe

                      value
color shape                
green round  0.05 -1.687948
             0.95  1.280259
      square 0.05 -1.733411
             0.95  1.528829
red   round  0.05 -1.253146
             0.95  1.504702
      square 0.05 -1.331865
             0.95  1.716751

as given by

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'id': np.arange(200),
    'color': ['red'] * 100   ['green'] * 100,
    'shape': (['round'] * 50   ['square'] * 50) * 2,
    'value': np.random.default_rng(seed=0).standard_normal(200),
}).groupby(['color', 'shape'])['value'].quantile([0.05, 0.95]).to_frame()

I know that I can set the name of the last level with

df.index = df.index.set_names('quantile', level=-1)

But is there any way to do this with any one of the dataframe chaining methods, such that I do not have to assign the dataframe to a variable first? Similar to how I could rename the dataframe columns with, e.g., .rename(columns={'value': 'val'}), but for the index labels? I've looked at the docs for .rename and .rename_axis, but could not figure out how to do this.

CodePudding user response:

You can use rename_axis:

df.rename_axis(index={None:'quantile'}, inplace=True)

Output:

                          value
color shape  quantile          
green round  0.05     -1.687948
             0.95      1.280259
      square 0.05     -1.733411
             0.95      1.528829
red   round  0.05     -1.253146
             0.95      1.504702
      square 0.05     -1.331865
             0.95      1.716751
  •  Tags:  
  • Related