pandas.Categorical.rename_categories — pandas 3.0.0.dev0+2104.ge637b4290d documentation (original) (raw)

Categorical.rename_categories(new_categories)[source]#

Rename categories.

This method is commonly used to re-label or adjust the category names in categorical data without changing the underlying data. It is useful in situations where you want to modify the labels used for clarity, consistency, or readability.

Parameters:

new_categorieslist-like, dict-like or callable

New categories which will replace old categories.

Returns:

Categorical

Categorical with renamed categories.

Raises:

ValueError

If new categories are list-like and do not have the same number of items than the current categories or do not validate as categories

Examples

c = pd.Categorical(["a", "a", "b"]) c.rename_categories([0, 1]) [0, 0, 1] Categories (2, int64): [0, 1]

For dict-like new_categories, extra keys are ignored and categories not in the dictionary are passed through

c.rename_categories({"a": "A", "c": "C"}) ['A', 'A', 'b'] Categories (2, object): ['A', 'b']

You may also provide a callable to create the new categories

c.rename_categories(lambda x: x.upper()) ['A', 'A', 'B'] Categories (2, object): ['A', 'B']