Reorder levels of MultiIndex in a pandas DataFrame
It's better to use reorder_levels
to manipulate the order of MultiIndex levels. Just pass in a list of the level names/numbers in the order you want:
>>> df.reorder_levels(['Letter','Color','Number'])
Value
Letter Color Number
a Red 1 41
Green 1 56
b Red 1 43
Green 1 42
c Red 1 89
Green 1 18
a Red 2 55
Green 2 93
b Red 2 64
Green 2 9
c Red 2 21
Green 2 93
There's also swaplevel
if you simply want to swap the positions of two levels.
Inplace Modification
Call MultiIndex.reorder_levels
, then assign the new index to your DataFrame.
df.index = df.index.reorder_levels(['Letter', 'Color', 'Number'])
df
Value
Letter Color Number
a Red 1 41
Green 1 56
b Red 1 43
Green 1 42
c Red 1 89
Green 1 18
a Red 2 55
Green 2 93
b Red 2 64
Green 2 9
c Red 2 21
Green 2 93
Since Index objects are immutable, you cannot get over creating a new Index, but you can avoid duplicating your data by otherwise calling df.reorder_levels
.