3

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

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.