Multi Index Sorting in Pandas

前端 未结 1 828
旧时难觅i
旧时难觅i 2020-12-07 11:37

I have a dataset with multi-index columns in a pandas df that I would like to sort by values in a specific column. I have tried using sortindex and sortlevel but haven\'t b

相关标签:
1条回答
  • 2020-12-07 12:19

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

    In [11]: df.sort_values([('Group1', 'C')], ascending=False)
    Out[11]: 
      Group1       Group2      
           A  B  C      A  B  C
    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 into thinking you want to sort first by Group1 then by C.


    Note: Originally used .sort since deprecated then removed in 0.20, in favor of .sort_values.

    0 讨论(0)
提交回复
热议问题