Skip to main content
`Ctrl`+`K`

# pandas.MultiIndex.remove_unused_levels

MultiIndex.remove_unused_levels()

  Create new MultiIndex from current that removes unused levels.

  Unused level(s) means levels that are not expressed in the labels. The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. It will also be .equals() to the original.

  The remove_unused_levels method is useful in cases where you have a MultiIndex with hierarchical levels, but some of these levels are no longer needed due to filtering or subsetting operations. By removing the unused levels, the resulting MultiIndex becomes more compact and efficient, which can improve performance in subsequent operations.

  Returns:
    MultiIndex

      A new MultiIndex with unused levels removed.

  See also

  `MultiIndex.droplevel`

    Remove specified levels from a MultiIndex.

  `MultiIndex.reorder_levels`

    Rearrange levels of a MultiIndex.

  `MultiIndex.set_levels`

    Set new levels on a MultiIndex.

  Examples

      >>> mi = pd.MultiIndex.from_product([range(2), list("ab")])
      >>> mi
      MultiIndex([(0, 'a'),
                  (0, 'b'),
                  (1, 'a'),
                  (1, 'b')],
                 )

      >>> mi[2:]
      MultiIndex([(1, 'a'),
                  (1, 'b')],
                 )

  The 0 from the first level is not represented and can be removed

      >>> mi2 = mi[2:].remove_unused_levels()
      >>> mi2.levels
      FrozenList([[1], ['a', 'b']])