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

Getting a specific part from multiindex df, without losing level 0 index

Imagine you have the following multiindexed dataframe

pd.DataFrame({('0-Engajados', 'affiliate'): 119,
     ('0-Engajados', 'attendance bot'): 7,
     ('1-Onboarding + Retorno', 'affiliate'): 118,
     ('1-Onboarding + Retorno', 'attendance bot'): 7})

And you wanted to grab everyone who has a level 0 index equal ‘0-Engajados’ but without losing, the index part. It is worh noting that the second index values vary, so iloc not quite an option.

Wanted end result

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

pd.DataFrame({('0-Engajados', 'affiliate'): 119,
     ('0-Engajados', 'attendance bot'): 7})

I tried df.loc['0-Engajados']

but that loses me the first index is there a way to grab it without losing it?

>Solution :

You can wrap your selection in a list to preserve its level:

import pandas as pd

df = pd.DataFrame({('0-Engajados', 'affiliate'): [119],
     ('0-Engajados', 'attendance bot'): [7],
     ('1-Onboarding + Retorno', 'affiliate'): [118],
     ('1-Onboarding + Retorno', 'attendance bot'): [7]})

print(df)
  0-Engajados                1-Onboarding + Retorno               
    affiliate attendance bot              affiliate attendance bot
0         119              7                    118              7


print(df.loc[:, ['0-Engajados']])
  0-Engajados               
    affiliate attendance bot
0         119              7
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