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
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?
CodePudding user response:
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