Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas set index name for single level

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading