Read category metadata
Inspect the distinct labels and internal integer representation of a categorical DataFrame column.
Pandas · Pipe
Series.cat provides access to categorical properties and operations. In a DataFrame workflow, select a categorical column and use .cat on the resulting Series.
The cat accessor exposes categorical properties and operations for a Series whose values use pandas' categorical dtype. Access it through a categorical DataFrame column, then call accessor attributes or methods such as categories and codes.
Series.cat| Name | Type | Description |
|---|---|---|
data | Series or CategoricalIndex | The Series or CategoricalIndex to which the categorical accessor is attached. |
An accessor object for categorical properties of the Series values.
cat is an accessor object for categorical properties.cat in DataFrame workflows.cat applies to categorical Series values; a regular object- or string-typed column must first be converted to categorical dtype.import pandas as pd
df = pd.DataFrame({"animal": ["cat", "dog", "cat"]})
df["animal"] = df["animal"].astype("category")
print(df["animal"].cat.categories.tolist())
print(df["animal"].cat.codes.tolist())Convert a column to categorical data, then inspect its categories and integer codes.
Inspect the distinct labels and internal integer representation of a categorical DataFrame column.
Apply category-level transformations to a selected DataFrame column.
Work with categorical columns while retaining pandas indexing and slicing behavior.
cat accessor provide?cat is an accessor for categorical properties of Series values. For a DataFrame, select a categorical column first, for example df["animal"].cat.categories.
Follow-up: How would you make a non-categorical column usable with cat? Convert it with astype("category") or assign a categorical dtype.
cat from a DataFrame?A DataFrame column can be categorical when constructed with dtype="category" or converted afterward. Selecting that column returns a Series on which the accessor is available.
Follow-up: What must be preserved when assigning categorical values? The assigned values must already belong to the column's categories.
cat a DataFrame-wide accessor?The accessor exposes categorical metadata and transformations, including category labels and category codes. Operations are performed on the Series selected from the DataFrame rather than directly on the DataFrame object.
Follow-up: What happens if a row selection changes the result to a non-categorical Series? The category dtype may not be preserved for a single-row result, so the accessor may no longer be available.
pandas.Series.cat.categoriespandas.Series.cat.codespandas.Series.cat.rename_categoriespandas.Series.cat.set_categoriespandas.Series.cat.remove_unused_categories