Skip to main content
`Ctrl`+`K`

# pandas.Series.swaplevel

Series.swaplevel(i=-2, j=-1, copy=<no_default>)

  Swap levels i and j in a `MultiIndex`.

  Default is to swap the two innermost levels of the index.

  Parameters:
    i, j int or str

      Levels of the indices to be swapped. Can pass level name as string.

    copy bool, default False

      This keyword is now ignored; changing its value will have no impact on the method.

      Deprecated since version 3.0.0: This keyword is ignored and will be removed in pandas 4.0. Since pandas 3.0, this method always returns a new object using a lazy copy mechanism that defers copies until necessary (Copy-on-Write). See the user guide on Copy-on-Write for more details.

  Returns:
    Series

      Series with levels swapped in MultiIndex.

  See also

  `DataFrame.swaplevel`

    Swap levels i and j in a `DataFrame`.

  `Series.reorder_levels`

    Rearrange index levels using input order.

  `MultiIndex.swaplevel`

    Swap levels i and j in a `MultiIndex`.

  Examples

      >>> s = pd.Series(
      ...     ["A", "B", "A", "C"],
      ...     index=[
      ...         ["Final exam", "Final exam", "Coursework", "Coursework"],
      ...         ["History", "Geography", "History", "Geography"],
      ...         ["January", "February", "March", "April"],
      ...     ],
      ... )
      >>> s
      Final exam  History    January     A
                  Geography  February    B
      Coursework  History    March       A
                  Geography  April       C
      dtype: str

  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-wise in a similar manner. Note that column-wise is the default behavior. By not supplying any arguments for i and j, we swap the last and second to last indices.

      >>> s.swaplevel()
      Final exam  January   History       A
                  February  Geography     B
      Coursework  March     History       A
                  April     Geography     C
      dtype: str

  By supplying one argument, we can choose which index to swap the last index with. We can for example swap the first index with the last one as follows.

      >>> s.swaplevel(0)
      January     History     Final exam      A
      February    Geography   Final exam      B
      March       History     Coursework      A
      April       Geography   Coursework      C
      dtype: str

  We can also define explicitly which indices we want to swap by supplying values for both i and j. Here, we for example swap the first and second indices.

      >>> s.swaplevel(0, 1)
      History     Final exam  January         A
      Geography   Final exam  February        B
      History     Coursework  March           A
      Geography   Coursework  April           C
      dtype: str