Categorical dtype (Pandas)

The category dtype stores a column as a fixed set of distinct values plus integer codes pointing into them, instead of repeating the full strings. It can save memory for repeated labels and can model ordered categories.

Pandas

A categorical array stores a collection of allowed categories and integer codes referring to them. It can reduce storage when many rows repeat a small set of labels; the categories also cost memory, so it is not automatically smaller for nearly unique values.

Ordered categories declare an order such as low, medium, high independently of alphabetical order. In Pandas 1.5 through 3.1, constructing a Categorical with an explicit category list turns values outside that list into missing entries; Pandas 3.1 warns that future versions will reject them. Assigning a new, unlisted category to an existing categorical Series instead raises TypeError; add the category first if it is valid.

Access the allowed values through s.cat.categories and choose whether new labels should be rejected or incorporated. A category list is useful schema information, but a missing result after conversion must still be checked rather than assumed to be an originally missing observation.

Syntax

s.astype('category')  |  pd.Categorical(values, categories, ordered=True)

Examples

Python

import pandas as pd
created = pd.Series(pd.Categorical(["low", "medium"], categories=["low", "high"]))
print("Absent after construction:", created.isna().tolist())
existing = pd.Series(["low", "high"], dtype="category")
try:
    existing.iloc[0] = "medium"
except TypeError as error:
    print(type(error).__name__ + ": " + str(error))
expanded = existing.cat.add_categories(["medium"])
expanded.iloc[0] = "medium"
print(expanded.tolist())

Output:

Absent after construction: [False, True]
TypeError: Cannot setitem on a Categorical with a new category (medium), set the categories first
['medium', 'high']

Learn it in a lesson

See also

Back to the Dictionary