Skip to content

Commit 302a2f0

Browse files
committed
Add examples to documentation for DataFrame.swaplevel
1 parent 2e7e3e2 commit 302a2f0

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
@@ -6278,6 +6278,57 @@ def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame:
62786278
Returns
62796279
-------
62806280
DataFrame
6281+
6282+
Examples
6283+
--------
6284+
>>> df = pd.DataFrame(
6285+
... {"Grade": ["A", "B", "A", "C"]},
6286+
... index=[
6287+
... ["Final exam", "Final exam", "Coursework", "Coursework"],
6288+
... ["History", "Geography", "History", "Geography"],
6289+
... ["January", "February", "March", "April"],
6290+
... ],
6291+
... )
6292+
>>> df
6293+
Grade
6294+
Final exam History January A
6295+
Geography February B
6296+
Coursework History March A
6297+
Geography April C
6298+
6299+
In the following example, we will swap the levels of the indices.
6300+
Here, we will swap the levels column-wise, but levels can be swapped row-wise
6301+
in a similar manner. Note that column-wise is the default behaviour.
6302+
By not supplying any arguments for i and j, we swap the last and second to
6303+
last indices.
6304+
6305+
>>> df.swaplevel()
6306+
Grade
6307+
Final exam January History A
6308+
February Geography B
6309+
Coursework March History A
6310+
April Geography C
6311+
6312+
By supplying one argument, we can choose which index to swap the last
6313+
index with. We can for example swap the first index with the last one as
6314+
follows.
6315+
6316+
>>> df.swaplevel(0)
6317+
Grade
6318+
January History Final exam A
6319+
February Geography Final exam B
6320+
March History Coursework A
6321+
April Geography Coursework C
6322+
6323+
We can also define explicitly which indices we want to swap by supplying values
6324+
for both i and j. Here, we for example swap the first and second indices.
6325+
6326+
>>> df.swaplevel(0, 1)
6327+
Grade
6328+
History Final exam January A
6329+
Geography Final exam February B
6330+
History Coursework March A
6331+
Geography Coursework April C
62816332
"""
62826333
result = self.copy()
62836334

0 commit comments

Comments
 (0)