pandas.MultiIndex.remove_unused_levels

MultiIndex.remove_unused_levels(self)[source]

Create a new MultiIndex from the current that removes unused levels, meaning that they 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.

New in version 0.20.0.

Returns:
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']])
Scroll To Top