Multi-Index Sorting in Pandas

后端 未结 5 1769
暖寄归人
暖寄归人 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:23

    If you want try to avoid multiple swaps within a very deep MultiIndex, you also could try with this:

    1. Slicing by level X (by list comprehension + .loc + IndexSlice)
    2. Sort the desired level (sortlevel(2))
    3. Concatenate every group of level X indexes

    Here you have the code:

    import pandas as pd
    idx = pd.IndexSlice
    g = pd.concat([grouped.loc[idx[i,:,:],:].sortlevel(2) for i in grouped.index.levels[0]])
    g
    

提交回复
热议问题