Skip to content
Open
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
42 changes: 29 additions & 13 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2607,14 +2607,18 @@ def swaplevel(self, i=-2, j=-1) -> MultiIndex:

Calling this method does not change the ordering of the values.

Default is to swap the last two levels of the MultiIndex.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the Parameters section can you describe what negative numbers mean?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Details for how negative numbers behave has been added.


Parameters
----------
i : int, str, default -2
First level of index to be swapped. Can pass level name as string.
Type of parameters can be mixed.
Type of parameters can be mixed. If i is a negative int, the first
level is indexed relative to the end of the MultiIndex.
j : int, str, default -1
Second level of index to be swapped. Can pass level name as string.
Type of parameters can be mixed.
Type of parameters can be mixed. If j is a negative int, the second
level is indexed relative to the end of the MultiIndex.

Returns
-------
Expand All @@ -2626,24 +2630,36 @@ def swaplevel(self, i=-2, j=-1) -> MultiIndex:
Series.swaplevel : Swap levels i and j in a MultiIndex.
DataFrame.swaplevel : Swap levels i and j in a MultiIndex on a
particular axis.

Examples
--------
>>> mi = pd.MultiIndex(
... levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
... levels=[["a", "b"], ["bb", "aa"], ["aaa", "bbb"]],
... codes=[[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 0]],
... )
>>> mi
MultiIndex([('a', 'bb'),
('a', 'aa'),
('b', 'bb'),
('b', 'aa')],
MultiIndex([('a', 'bb', 'bbb'),
('a', 'aa', 'aaa'),
('b', 'bb', 'bbb'),
('b', 'aa', 'aaa')],
)
>>> mi.swaplevel(0, 1)
MultiIndex([('bb', 'a'),
('aa', 'a'),
('bb', 'b'),
('aa', 'b')],
>>> mi.swaplevel()
MultiIndex([('a', 'bbb', 'bb'),
('a', 'aaa', 'aa'),
('b', 'bbb', 'bb'),
('b', 'aaa', 'aa')],
)
>>> mi.swaplevel(0)
MultiIndex([('bbb', 'bb', 'a'),
('aaa', 'aa', 'a'),
('bbb', 'bb', 'b'),
('aaa', 'aa', 'b')],
)
>>> mi.swaplevel(0, 1)
MultiIndex([('bb', 'a', 'bbb'),
('aa', 'a', 'aaa'),
('bb', 'b', 'bbb'),
('aa', 'b', 'aaa')],
)
"""
new_levels = list(self.levels)
new_codes = list(self.codes)
Expand Down
Loading