Search code examples
pythonpandasmulti-index

Slice groupby.describe dataframe


I have a dataframe that looks like the following:

enter image description here

I'd like to take all of the outer index, and only the mean and std from the inner index.

I attempted to use idx = pd.IndexSlice in the following ways: desc_df.loc[idx[:]] yields the entire dataframe

desc_df.loc[idx[3:4,:]] yields only index 3 and 4

desc_df.loc[idx[3:4,'mean']] fails with mean is no in the columns

desc_df.loc[idx[(3:4,'mean')]] fails...etc

How do I execute my desired use case?


Solution

  • idx = pd.IndexSlice
    
    df.loc[idx[:, ['mean', 'std']], :]
          #|   |       |            |
          #|   |       |            All columns    
          #|   |       |                
          #|   |      'mean' and 'std' locs of 1st level
          #|   |
          #|   Everything 0th level
          #|
          #Slice row index