How can I sort a multi-index dataframe while respecting the organization of levels?
E.g. given the following df
, say we sort it according to C
(e.g. in descending order):
C D E
A B
bar one -0.346528 1.528538 1
three -0.136710 -0.147842 1
flux six 0.795641 -1.610137 1
three 1.051926 -1.316725 2
foo five 0.906627 0.717922 0
one -0.152901 -0.043107 2
two 0.542137 -0.373016 2
two 0.329831 1.067820 1
We should get:
C D E
A B
bar three -0.136710 -0.147842 1
one -0.346528 1.528538 1
flux three 1.051926 -1.316725 2
six 0.795641 -1.610137 1
foo five 0.906627 0.717922 0
two 0.542137 -0.373016 2
two 0.329831 1.067820 1
two -0.152901 -0.043107 2
Note that what I mean by "respecting its index structure" is sorting the leafs of the dataframe without changing the ordering of higher-level indices. In other words, I want to sort the second level while keeping the ordering of the the first level untouched.
What about doing the same in ascending order?
I read these two threads (yes, with the same title):
but they sort the dataframes according to a different criteria (e.g. index names, or a specific column in a group).