Multi-Index Sorting in Pandas

后端 未结 5 1765
暖寄归人
暖寄归人 2020-12-13 02:58

I have a multi-index DataFrame created via a groupby operation. I\'m trying to do a compound sort using several levels of the index, but I can\'t seem to find a sort functi

5条回答
  •  -上瘾入骨i
    2020-12-13 03:25

    To sort a MultiIndex by the "index columns" (aka. levels) you need to use the .sort_index() method and set its level argument. If you want to sort by multiple levels, the argument needs to be set to a list of level names in sequential order.

    This should give you the DataFrame you need:

    df.groupby(['Manufacturer',
                'Product Name', 
                'Launch Date']
              ).sum().sort_index(level=['Manufacturer','Launch Date'])
    

提交回复
热议问题