pandas.CategoricalIndex.remove_unused_categories#

CategoricalIndex.remove_unused_categories()[source]#

Remove categories which are not used.

This method is useful when working with datasets that undergo dynamic changes where categories may no longer be relevant, allowing to maintain a clean, efficient data structure.

Returns:
CategoricalIndex

CategoricalIndex with unused categories dropped.

See also

CategoricalIndex.rename_categories

Rename categories.

CategoricalIndex.reorder_categories

Reorder categories.

CategoricalIndex.add_categories

Add new categories.

CategoricalIndex.remove_categories

Remove the specified categories.

CategoricalIndex.set_categories

Set the categories to the specified ones.

Examples

>>> ci = pd.CategoricalIndex(["a", "c", "b", "c", "d"])
>>> ci
CategoricalIndex(['a', 'c', 'b', 'c', 'd'], categories=['a', 'b', 'c', 'd'],
                 ordered=False, dtype='category')
>>> ci = ci[[0, 1, 0, 1, 1]]
>>> ci
CategoricalIndex(['a', 'c', 'a', 'c', 'c'], categories=['a', 'b', 'c', 'd'],
                 ordered=False, dtype='category')
>>> ci.remove_unused_categories()
CategoricalIndex(['a', 'c', 'a', 'c', 'c'], categories=['a', 'c'],
                 ordered=False, dtype='category')