Sorting Multi-Index to full depth (Pandas)

前端 未结 3 1862
暖寄归人
暖寄归人 2021-02-07 08:19

I have a dataframe which Im loading from a csv file and then setting the index to few of its columns (usually two or three) by the set_index method. The idea is to

3条回答
  •  野性不改
    2021-02-07 09:07

    I realize some time has passed but I seem to have had the same problem as @idoda did, with the accepted answer not working on MultiIndex dataframes when the dataframes may have multiple indexes on both the columns and index. The trick, not currently shown here, is that there is an "axis" option which defaults to zero but can also be set to 1.

    For example if you try:

    df.sortlevel(inplace=True,sort_remaining=True)
    

    And are still getting lexsort errors it may be relevant to know that their is a default "axis=0" kwarg in there. Thus you can also try adding

    df.sortlevel(axis=1,inplace=True,sort_remaining=True)
    

    Which should sort the other direction. If you don't want to think about it, you can just brute force it with:

    df.sortlevel(axis=0,inplace=True,sort_remaining=True)
    df.sortlevel(axis=1,inplace=True,sort_remaining=True)
    

    That should fully sort both columns and row indexes at all levels. I had the same problem here and couldn't get a full lexsort with the suggested answer but a bit of research showed that even with "sort_remaining" True the sortlevel applies to only a single axis. These snippets are the solution to that which appear to be the current pythonic native answer. Hope somebody finds it helpful!

提交回复
热议问题