Lisle
Lisle

Reputation: 1690

Sorting Multi Index in Pandas differently for each level

I have a dataframe with an index of 3 levels. I need to sort the index by each level but in different ways. What can achieve this?

Have a dataframe (df) as:

                     other columns
color shape    count              
red   circle   1                 x
      triangle 3                 x
               2                 x
blue  circle   4                 x
      triangle 2                 x

and I want a new df where color is sorted ascending, shape is descending, and count is ascending:

                     other columns
color shape       count              
blue  triangle    2                 x
      circle      4                 x
red   triangle    2                 x
                  3                 x
      circle      1                 x

Upvotes: 3

Views: 791

Answers (1)

Scott Boston
Scott Boston

Reputation: 153500

Use ascending parameter with a list of booleans:

df.sort_index(ascending=[True, False, True])

Output:

                     other columns
color shape    count              
blue  triangle 2                 x
      circle   4                 x
red   triangle 2                 x
               3                 x
      circle   1                 x

Upvotes: 8

Related Questions