Sub topic 13
Pitfalls and best practices
This chapter assumes you have read the earlier chapters on categories and codes, the .cat accessor, ordered categoricals, and groupby with observed. It collects the mistakes that come up most often and the habits that prevent them.
Decide first whether a column should be categorical
A categorical pays off when a column has few distinct values that repeat many times. If most values are unique, such as IDs or free text, the column still stores every distinct value plus a code per row, so it can use more memory than object and give no speedup.
Measure with memory_usage(deep=True) before converting a large column. Do not assume.
Common pitfalls
The code below shows two of the most frequent surprises and a fix for each.
import pandas as pd
from pandas.api.types import union_categoricals
a = pd.Series(["x", "y"], dtype="category")
b = pd.Series(["y", "z"], dtype="category")
# Pitfall 1: different categories fall back to object on concat
print(pd.concat([a, b]).dtype) # object
# Pitfall 2: assigning a value outside the categories fails
try:
a.iloc[0] = "z"
except (TypeError, ValueError) as err:
print("error:", type(err).__name__)
# Fix 1: merge the categories explicitly
combined = pd.Series(union_categoricals([a, b]))
print(combined.dtype) # category
# Fix 2: share one dtype from the start
shared = pd.CategoricalDtype(["x", "y", "z"])
both = pd.concat([a.astype(shared), b.astype(shared)])
print(both.dtype) # categoryThe exception type depends on your pandas version, so the example catches both TypeError and ValueError. The fix for the error is to call add_categories first.
| Pitfall | Symptom | Fix |
|---|---|---|
| Concatenating columns with different categories | Result silently becomes `object` | Use `union_categoricals` or a shared `CategoricalDtype` |
| Assigning a value that is not a category | Error on assignment | Call `cat.add_categories` first |
| Grouping without setting `observed` | Rows for unused categories, or a version-dependent default | Always pass `observed=True` or `observed=False` |
| Comparing unordered categoricals with `<` or `max` | `TypeError` | Declare `ordered=True`, or compare as strings |
| Doing arithmetic on a categorical of numbers | Error or wrong results | Convert back with `astype(int)` or `astype(float)` first |
| Using `cat.codes` as a numeric feature | Model assumes a distance between levels | Use one-hot encoding unless the order is meaningful |
Pitfalls that hide
- Unused categories stay. Filtering rows does not remove categories, so
value_counts()still lists them with a count of 0. Callremove_unused_categories()after filtering when you do not want them. - Category order is not value order. An unordered categorical sorts by category position, which is alphabetical only when pandas inferred the categories. Set the order explicitly when it matters.
- Missing values are not categories.
NaNis stored as code-1and never appears incat.categories. Check withisna(). - The default for
observedhas changed. Older pandas defaulted toFalse, and newer releases move towardTrue. Passing it explicitly keeps results stable across versions. - File formats may drop the dtype. CSV loses categorical dtype, so convert again after reading or pass
dtype=toread_csv. Parquet keeps it.
Best practices
- Define a
CategoricalDtypein one shared place, with the categories andorderedflag, and apply it to every source. - Convert early, right after loading, so later steps use the smaller dtype.
- Pass
observedexplicitly in everygroupbyon a categorical key. - Clean up with
remove_unused_categories()after filtering or splitting data. - Use
ordered=Trueonly when the levels have a real order. - Check
df.dtypesafter merges, concatenations, and file reads to confirm the columns are still categorical.
Exercise
You concatenate two Series that both have dtype category, and the result has dtype object. What most likely caused this, and how do you keep the category dtype?
Show answer
The two Series had different category sets, so pandas could not keep a single categorical dtype. Either merge them with union_categoricals, or convert both to one shared CategoricalDtype (for example pd.CategoricalDtype(["x", "y", "z"])) before calling pd.concat.