Skip to content

Add example #43032

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 107 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6806,7 +6806,113 @@ def reorder_levels(self, order: Sequence[Axis], axis: Axis = 0) -> DataFrame:
Returns
-------
DataFrame
"""

Example
-------
>>> df = pd.DataFrame(np.random.randint(10, size=(4, 2)),
... index=[['a', 'a', 'b', 'b'],[1, 2, 1, 2]],
... columns=['one', 'two'])
>>> df.index.set_names(['index1', 'index2'], inplace=True)
>>> df
one two
index1 index2
a 1 7 4
2 4 1
b 1 4 1
2 3 8

Reorder levels by position

>>> df.reorder_levels([1, 0])
one two
index2 index1
1 a 7 4
2 a 4 1
1 b 4 1
2 b 3 8

The `reorder_levels` function returns unsorted index.
The selection of elements may not works and it will raise `UnsortedIndexError`.

>>> df.loc[(1, 'a'):(2, 'a')]
UnsortedIndexError: 'Key length (2) was greater than MultiIndex lexsort depth (0)'

To check if index is sorted or not, you can use `is_lexsorted` method on Index
and `lexsort_depth` to check sort depth.

>>> df.index.is_lexsorted()
False
>>> df.index.lexsort_depth
0

Multiindex object to be index and sliced properly. They need to be sorted,
for that we can use `sort_index` method.

>>> df = df.sort_index()
>>> df
one two
index2 index1
1 a 7 4
b 4 1
2 a 4 1
b 3 8
>>> df.index.is_lexsorted()
True
>>> df.index.lexsort_depth
2

Now, selection of elements works as expected.

>>> df.loc[(1, 'a'):(2, 'a')]
one two
index2 index1
1 a 7 4
b 4 1
2 a 4 1

Reorder levels by lebels

>>> df.reorder_levels(['index2', 'index1']).sort_index()
one two
index2 index1
1 a 7 4
b 4 1
2 a 4 1
b 3 8

Length of order must be same as number of levels.
By default, it reorder levels by index, to reorder by columns, use axis = 1.

>>> df = pd.DataFrame(np.random.randint(10, size=(4, 3)),
... index=[1, 2, 3, 4],
... columns=[['A', 'A', 'B'],['one', 'two', 'one']])
>>> df.columns.set_names(['column1', 'column2'], inplace=True)
>>> df
column1 A B
column2 one two one
1 6 1 8
2 5 2 3
3 8 4 1
4 5 2 9

>>> df.reorder_levels([1, 0], axis=1)
column2 one two one
column1 A A B
1 6 1 8
2 5 2 3
3 8 4 1
4 5 2 9

To sort column index, we can use same `sort_index()` method with parameter `axis=1`

>>> df.reorder_levels([1, 0], axis=1).sort_index(axis=1)
column2 one two
column1 A B A
1 6 8 1
2 5 3 2
3 8 1 4
4 5 9 2
"""
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
raise TypeError("Can only reorder levels on a hierarchical axis.")
Expand Down