Pandas DataFrame | reorder_levels method
Start your free 7-days trial now!
Pandas DataFrame.reorder_levels(~)
method changes the ordering of levels.
Parameters
1. order
link | list<int>
or list<string>
The new order of the levels. You can refer to the levels either by integer index or by their name.
2. axis
link | int
or string
| optional
Whether to reorder index or column levels:
Axis | Description |
---|---|
| Reorder levels of the index. |
| Reorder levels of the column. |
By default, axis=0
.
Return Value
A new DataFrame
with the levels reordered.
Examples
Reordering levels of multi-index row
Consider the following DataFrame with multi-index rows:
index = [("A", "alice"), ("A", "bob"),("A", "cathy"),("B", "david"),("B", "eric")]df
aA alice 2 bob 3 cathy 4B david 5 eric 6
To swap the ordering of the row levels:
df.reorder_levels([1,0])
aalice A 2bob A 3cathy A 4david B 5eric B 6
Here, the argument [1,0]
means the following:
1
st level (inner level in this case) becomes the outer level.0
th level (outer level) becomes the inner level.
Reordering levels of multi-index column
Consider the following DataFrame with multi-index columns:
index = [("A", "alice"), ("A", "bob"),("A", "cathy"), ("B", "david"),("B", "eric")]df
A B alice bob cathy david eric0 2 3 4 5 6
To swap the ordering of the column levels, set axis=1
like so:
df.reorder_levels([1,0], axis=1)
alice bob cathy david eric A A A B B0 2 3 4 5 6