- API reference
- Series
- pandas.Serie...
pandas.Series.swaplevel#
- Series.swaplevel(i=-2,j=-1,copy=None)[source]#
Swap levels i and j in a
MultiIndex.Default is to swap the two innermost levels of the index.
- Parameters:
- i, jint or str
Levels of the indices to be swapped. Can pass level name as string.
- copybool, default True
Whether to copy underlying data.
Note
Thecopy keyword will change behavior in pandas 3.0.Copy-on-Writewill be enabled by default, which means that all methods with acopy keyword will use a lazy copy mechanism to defer the copy andignore thecopy keyword. Thecopy keyword will be removed in afuture version of pandas.
You can already get the future behavior and improvements throughenabling copy on write
pd.options.mode.copy_on_write=True
- Returns:
- Series
Series with levels swapped in MultiIndex.
Examples
>>>s=pd.Series(...["A","B","A","C"],...index=[...["Final exam","Final exam","Coursework","Coursework"],...["History","Geography","History","Geography"],...["January","February","March","April"],...],...)>>>sFinal exam History January A Geography February BCoursework History March A Geography April Cdtype: object
In the following example, we will swap the levels of the indices.Here, we will swap the levels column-wise, but levels can be swapped row-wisein a similar manner. Note that column-wise is the default behaviour.By not supplying any arguments for i and j, we swap the last and second tolast indices.
>>>s.swaplevel()Final exam January History A February Geography BCoursework March History A April Geography Cdtype: object
By supplying one argument, we can choose which index to swap the lastindex with. We can for example swap the first index with the last one asfollows.
>>>s.swaplevel(0)January History Final exam AFebruary Geography Final exam BMarch History Coursework AApril Geography Coursework Cdtype: object
We can also define explicitly which indices we want to swap by supplying valuesfor both i and j. Here, we for example swap the first and second indices.
>>>s.swaplevel(0,1)History Final exam January AGeography Final exam February BHistory Coursework March AGeography Coursework April Cdtype: object