Sub topic 1
Why categorical data exists in pandas
Prerequisites
This chapter assumes basic Python, pandas Series and DataFrame use, and familiarity with dtypes such as object and int64. You should also know basic groupby and value_counts.
Why categorical data exists
A categorical column contains a limited set of repeated values, such as "small", "medium", and "large". Pandas stores the distinct values once as categories and stores each row as an integer code pointing to a category.
This representation can use less memory than an object column, especially when a large column contains few distinct values. It also records the column's allowed values and, optionally, their logical order.
Creating categorical columns
Convert an existing column with astype("category"):
import pandas as pd
df = pd.DataFrame({"size": ["small", "large", "medium", "small", "large"]})
df["size"] = df["size"].astype("category")
print(df["size"].dtype)For a defined order or a controlled vocabulary, use CategoricalDtype:
size_type = pd.CategoricalDtype(
categories=["small", "medium", "large"],
ordered=True,
)
df["size"] = df["size"].astype(size_type)Categories, codes, and the `.cat` accessor
The .cat accessor provides categorical-specific operations:
print(df["size"].cat.categories.tolist())
print(df["size"].cat.codes.tolist())Codes are implementation details, not stable identifiers. Missing values use the code -1, so do not treat codes as ordinary data without handling missing values.
You can inspect a categorical through this model:
| Part | Meaning |
|---|---|
| Categories | The distinct allowed labels |
| Codes | Integer positions referring to those labels |
| `.cat` | Accessor for categorical operations |
Measuring memory and performance gains
Measure memory with memory_usage(deep=True):
n = 300_000
s_obj = pd.Series(["red", "green", "blue"] * (n // 3))
s_cat = s_obj.astype("category")
print(s_obj.memory_usage(deep=True))
print(s_cat.memory_usage(deep=True))The categorical version usually saves memory because it stores the strings once and uses compact codes for rows. Grouping and counting can also benefit, but actual performance depends on the operation and data shape. Measure representative data before relying on a gain.
Exercise
Why can a categorical column use less memory than an object column?
Show answer
It stores each distinct label once and stores integer codes for the rows that refer to those labels.