Sub topic 3
Groupby and Unobserved Categories in pandas
Assume you know how to create pandas Series and DataFrames, use groupby, and work with basic dtypes. This chapter focuses on how categorical columns behave when data is grouped, combined, saved, and prepared for models.
Groupby and unobserved categories
A categorical column can contain categories that do not appear in the current rows. For example, a status column might define new, active, and closed, even when no row is currently active.
By default, groupby includes these unobserved categories. Use observed=True when you want only categories present in the data.
import pandas as pd
level_type = pd.CategoricalDtype(["low", "mid", "high"])
df = pd.DataFrame({
"level": pd.Series(["low", "low", "high"], dtype=level_type),
"value": [1, 2, 3],
})
print(df.groupby("level", observed=False)["value"].sum())
print(df.groupby("level", observed=True)["value"].sum())The first result includes mid with a total of zero. The second result omits it.
Combining categoricals from different sources
Concatenating categoricals preserves the categorical dtype only when their category definitions are compatible. If two columns have different categories or ordering, pandas may fall back to object.
Use union_categoricals when you need one categorical containing the categories from multiple sources.
from pandas.api.types import union_categoricals
left = pd.Series(["small", "medium"], dtype="category")
right = pd.Series(["large", "small"], dtype="category")
combined = union_categoricals([left.array, right.array])
print(combined.categories.tolist())Keeping categorical dtype during file operations
CSV stores text, not pandas dtype metadata. Reading a CSV usually returns an object column unless you provide a dtype.
Parquet and Feather can preserve categorical metadata. For portable CSV workflows, define the dtype while reading:
size_type = pd.CategoricalDtype(["small", "medium", "large"], ordered=True)
df = pd.read_csv("items.csv", dtype={"size": size_type})Encoding categoricals for machine learning
Use one-hot encoding for nominal categories, where order has no meaning. Use ordered integer codes only when the model and feature have a meaningful order. The code -1 represents missing data, so handle missing values before training.
Pitfalls and best practices
| Situation | Safer choice |
|---|---|
| Unused groups are unwanted | Set `observed=True` |
| Categories have different definitions | Align dtypes or use `union_categoricals` |
| CSV loses category metadata | Pass `dtype` when reading |
| A nominal feature uses integer codes | Use one-hot encoding |
Exercise
Why can a groupby result contain a category with no input rows?
Show answer
Categorical columns retain their full category list, and groupby includes unobserved categories unless observed=True is set.