pandas slicing multiindex dataframe

Use xs for cross section

testdf2.xs('A', axis=1, level=1)

enter image description here

Or keep the column level with drop_level=False

testdf2.xs('A', axis=1, level=1, drop_level=False)

enter image description here


You can use:

idx = pd.IndexSlice
df = testdf2.loc[:, idx[['sum', 'count'], 'A']]
print (df)
                                                    sum count
Provider                                              A     A
Employer Year Division Name EmployeeId PersonId              
Z        2012 C        H    14         14        311.17   2.0
                                       15           NaN   NaN
         2013 C        H    14         14        386.29   2.0

Another solution:

df = testdf2.loc[:, (slice('sum','count'), ['A'])]
print (df)
                                                    sum count
Provider                                              A     A
Employer Year Division Name EmployeeId PersonId              
Z        2012 C        H    14         14        311.17   2.0
                                       15           NaN   NaN
         2013 C        H    14         14        386.29   2.0