Skip to content

Commit 3577010

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

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

pandas/core/frame.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6278,6 +6278,55 @@ 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({'Grade':['A','B','A','C']},
6285+
... index=[['Final exam', 'Final exam', 'Coursework',
6286+
... 'Coursework'],
6287+
... ['History','Geography','History','Geography'],
6288+
... ['January','February','March','April']])
6289+
>>> df
6290+
Grade
6291+
Final exam History January A
6292+
Geography February B
6293+
Coursework History March A
6294+
Geography April C
6295+
6296+
In the following example, we will swap the levels of the indices.
6297+
Here, we will swap the levels column-wise, but levels can be swapped row-wise
6298+
in a similar manner. Note that column-wise is the default behaviour.
6299+
By not supplying any arguments for i and j, we swap the last and second to
6300+
last indices.
6301+
6302+
>>> df.swaplevel()
6303+
Grade
6304+
Final exam January History A
6305+
February Geography B
6306+
Coursework March History A
6307+
April Geography C
6308+
6309+
By supplying one argument, we can choose which index to swap the last
6310+
index with. We can for example swap the first index with the last one as
6311+
follows.
6312+
6313+
>>> df.swaplevel(0)
6314+
Grade
6315+
January History Final exam A
6316+
February Geography Final exam B
6317+
March History Coursework A
6318+
April Geography Coursework C
6319+
6320+
We can also define explicitly which indices we want to swap by supplying values
6321+
for both i and j. Here, we for example swap the first and second indices.
6322+
6323+
>>> df.swaplevel(0, 1)
6324+
Grade
6325+
History Final exam January A
6326+
Geography Final exam February B
6327+
History Coursework March A
6328+
Geography Coursework April C
6329+
62816330
"""
62826331
result = self.copy()
62836332

0 commit comments

Comments
 (0)