Multi-Index Sorting in Pandas

后端 未结 5 1774
暖寄归人
暖寄归人 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条回答
  •  甜味超标
    2020-12-13 03:32

    This one liner works for me:

    In [1]: grouped.sortlevel(["Manufacturer","Product Launch Date"], sort_remaining=False)
    
                                                   Sales
    Manufacturer Product Name Product Launch Date       
    Apple        iPod         2001-10-23              34
                 iPad         2010-04-03              30
    Samsung      Galaxy       2009-04-27              24
                 Galaxy Tab   2010-09-02              22
    

    Note this works too:

    groups.sortlevel([0,2], sort_remaining=False)
    

    This wouldn't have worked when you originally posted over two years ago, because sortlevel by default sorted on ALL indices which mucked up your company hierarchy. sort_remaining which disables that behavior was added last year. Here's the commit link for reference: https://github.com/pydata/pandas/commit/3ad64b11e8e4bef47e3767f1d31cc26e39593277

提交回复
热议问题