Search code examples
pandassearchindexinghierarchical

Search a Pandas Dataframe having hierarchical indexing by a single column


I'm working with this dataframe:

import pandas as pd
df = pd.DataFrame([['A', 'one',  105], ['A', 'two',  101], ['A', 'three',  103],
                      ['B','one',  101], ['B','two',  1102], ['B','three',  1050]],
                   columns=['c1', 'c2', 'c3'])
df = df.set_index(['c1', 'c2'])
df

Which returns

               c3
c1    c2    
A     one     105
      two     101
      three   103
B     one     101
      two     1102
      three   1050

... and I'd like to sort by column c3, preserving rows and c1 sort, to get this:

              c3
c1    c2    
A     one     105
      three   103
      two     101
B     two     1102
      three   1050
      one     101

I've not been able to come up with a method that doesn't jumble the c1 sort. In particular, a final df.sort_index() returns KeyError: 'c1'


Solution

  • IIUC you can do:

    out = (df.sort_values(['c3','c1'],ascending=False)
          .reindex(df.index.get_level_values(0).unique(),level=0))
    

                c3
    c1 c2         
    A  one     105
       three   103
       two     101
    B  two    1102
       three  1050
       one     101