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
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!