Encode fixed categories
Represent a bounded label domain such as workflow states or product tiers.
Pandas · Function
pd.Categorical constructs a categorical array from values, with optional explicit categories and ordering. Explicit categories define permitted values; out-of-category inputs become missing.
pd.Categorical creates a categorical array from values, optionally using an explicit unique category set and an ordering flag. With ordered=True, sorting and comparisons use the category order; values outside an explicit category set become missing.
pandas.Categorical(values, categories=None, ordered=False, dtype=None, fastpath=<no_default>)| Name | Type | Description |
|---|---|---|
values | list-like | Input values used to construct the categorical. |
categories | Index-like, optional | Unique category labels; if omitted, pandas infers them from values. |
ordered | bool, default False | Whether the categorical has an ordered relationship; default False. |
dtype | CategoricalDtype or None, optional | Optional categorical dtype information used during construction. |
Categorical
import pandas as pd
values = pd.Categorical(
["low", "high", "medium", "unknown"],
categories=["low", "medium", "high"],
ordered=True,
)
print(values.categories.tolist())
print(values.ordered)
print(values.tolist())Creates an ordered categorical with an explicit category set; the value outside that set becomes missing.
Represent a bounded label domain such as workflow states or product tiers.
Ensure sorting follows a business-defined sequence rather than lexical order.
Normalize observed values against an allowed vocabulary and expose invalid labels as missing.
pd.Categorical represents a categorical variable with a limited set of possible values. Its categories can be inferred from the input or supplied explicitly, and ordered controls whether category order is meaningful.
Follow-up: What happens to an input value omitted from an explicit categories list? It becomes NaN.
When categories are omitted, pandas derives them from the unique input values, sorting them when possible and otherwise preserving their appearance order. Supplying categories lets you define the permitted vocabulary explicitly.
Follow-up: Why supply categories during construction? To establish a fixed set and control its order independently of the observed values.
An ordered categorical respects the sequence in its categories attribute when sorted. With ordered=False, the categorical is not treated as having an ordered relationship.
Follow-up: How can the category order be changed after construction? Use methods such as reorder_categories or set_categories.
pandas.CategoricalDtypepandas.CategoricalIndexCategorical.from_codesCategorical.as_orderedCategorical.as_unorderedCategorical.set_categoriesCategorical.reorder_categories