CiaranWelsh
CiaranWelsh

Reputation: 7681

Sorting a pandas DataFrame by one level of a MultiIndex

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

Upvotes: 5

Views: 5388

Answers (1)

piRSquared
piRSquared

Reputation: 294488

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

Upvotes: 9

Related Questions