Sort multiple indexes in Pandas

I have a multi-index column dataset in pandas df that I would like to sort by values ​​in a specific column. I tried using sortindex and sortlevel but could not get the results I am looking for. My dataset looks like this:

Group1 Group2 ABCABC 1 1 0 3 2 5 7 2 5 6 9 1 0 0 3 7 0 2 0 3 5 

I want to sort all the data and index by column C in group 1 in descending order so that my results look like this:

  Group1 Group2 ABCABC 2 5 6 9 1 0 0 1 1 0 3 2 5 7 3 7 0 2 0 3 5 

Is it possible to make this view with the structure in which my data is located, or do I need to exchange Group1 to the index side?

+45
python sorting pandas multi-index
Feb 06 '13 at 16:24
source share
1 answer

When sorting by MultiIndex, you need to contain a tuple that describes the column inside the list *:

 In [11]: df.sort([('Group1', 'C')], ascending=False) Out[11]: Group1 Group2 ABCABC 2 5 6 9 1 0 0 1 1 0 3 2 5 7 3 7 0 2 0 3 5 

* so as not to confuse pandas with what you want to sort first by Group1 and then by C.

+59
Feb 06 '13 at
source share



All Articles