Skip to content

Commit 0a2a200

Browse files
Add examples to documentation for DataFrame.swaplevel (#40269)
Co-authored-by: Marco Gorelli <[email protected]>
1 parent bed5ae2 commit 0a2a200

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

pandas/core/frame.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6464,6 +6464,57 @@ def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame:
64646464
Returns
64656465
-------
64666466
DataFrame
6467+
6468+
Examples
6469+
--------
6470+
>>> df = pd.DataFrame(
6471+
... {"Grade": ["A", "B", "A", "C"]},
6472+
... index=[
6473+
... ["Final exam", "Final exam", "Coursework", "Coursework"],
6474+
... ["History", "Geography", "History", "Geography"],
6475+
... ["January", "February", "March", "April"],
6476+
... ],
6477+
... )
6478+
>>> df
6479+
Grade
6480+
Final exam History January A
6481+
Geography February B
6482+
Coursework History March A
6483+
Geography April C
6484+
6485+
In the following example, we will swap the levels of the indices.
6486+
Here, we will swap the levels column-wise, but levels can be swapped row-wise
6487+
in a similar manner. Note that column-wise is the default behaviour.
6488+
By not supplying any arguments for i and j, we swap the last and second to
6489+
last indices.
6490+
6491+
>>> df.swaplevel()
6492+
Grade
6493+
Final exam January History A
6494+
February Geography B
6495+
Coursework March History A
6496+
April Geography C
6497+
6498+
By supplying one argument, we can choose which index to swap the last
6499+
index with. We can for example swap the first index with the last one as
6500+
follows.
6501+
6502+
>>> df.swaplevel(0)
6503+
Grade
6504+
January History Final exam A
6505+
February Geography Final exam B
6506+
March History Coursework A
6507+
April Geography Coursework C
6508+
6509+
We can also define explicitly which indices we want to swap by supplying values
6510+
for both i and j. Here, we for example swap the first and second indices.
6511+
6512+
>>> df.swaplevel(0, 1)
6513+
Grade
6514+
History Final exam January A
6515+
Geography Final exam February B
6516+
History Coursework March A
6517+
Geography Coursework April C
64676518
"""
64686519
result = self.copy()
64696520

0 commit comments

Comments
 (0)