5

I have a MultiIndexed pandas DataFrame that needs sorting by one of the indexers. Here is a snippet of the data:

gene                      VIM  
treatment dose time            
TGFb      0.1  2    -0.158406  
          1    2     0.039158  
          10   2    -0.052608  
          0.1  24    0.157153  
          1    24    0.206030  
          10   24    0.132580  
          0.1  48   -0.144209  
          1    48   -0.093910  
          10   48   -0.166819  
          0.1  6     0.097548  
          1    6     0.026664  
          10   6    -0.008032  

I'm looking to sort the data so that the time index is in ascending order. My first thoughts was to use pandas.sort_values but it seems this doesn't work on the index. Does anybody know of a way to do this? Thanks

1 Answer 1

9

Use sort_index specifying level:

df.sort_index(level=2)

Or

df.sort_index(level=-1)

Or

df.sort_index(level='time')

All yield:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

For my case, I found I needed to add sort_remaining=False to preserve the order of subsequent levels (in the OP's case, imagine having another index column after time whose order you want to preserve)

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.