Sub topic 10
Combining categoricals from different sources
This chapter assumes you know how a categorical stores categories and integer codes, how the .cat accessor works, and how pd.concat stacks Series. The problem here is that two categoricals can hold the same kind of data but carry different category sets. That happens often when data comes from separate files or tables.
What goes wrong with concat
pd.concat keeps the categorical dtype only when every input has the same categories. If the category sets differ, pandas can't reuse one set of integer codes, so it converts the result to object. The memory and speed benefits are lost, and you get no error.
import pandas as pd
a = pd.Series(["x", "y"], dtype="category")
b = pd.Series(["y", "z"], dtype="category")
print(pd.concat([a, b], ignore_index=True).dtype) # objectOrdering matters too. Two dtypes with the same categories in a different order are not equal, so they also fall back to object.
Choosing a strategy
| Situation | Approach |
|---|---|
| You know the full set of categories up front | Cast every input to one shared `CategoricalDtype` |
| Categories are only known from the data | `union_categoricals` |
| Inputs are ordered with different orders | Decide the order yourself, then cast |
Option 1: a shared dtype
When you define the categories yourself, a shared CategoricalDtype is the clearest option. It also fixes the category order, and values outside the list become missing, so mistakes show up as NaN instead of silently adding categories.
import pandas as pd
shared = pd.CategoricalDtype(["x", "y", "z"])
a = pd.Series(["x", "y"]).astype(shared)
b = pd.Series(["y", "z"]).astype(shared)
combined = pd.concat([a, b], ignore_index=True)
print(combined.dtype)
print(list(combined.cat.categories)) # ['x', 'y', 'z']Option 2: union_categoricals
union_categoricals builds the union of the categories for you. It returns a Categorical, which you can wrap in a Series.
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")
merged = pd.Series(union_categoricals([a, b]))
print(merged.dtype)
print(list(merged.cat.categories)) # ['x', 'y', 'z']
print(merged.tolist()) # ['x', 'y', 'y', 'z']New categories are listed in order of first appearance. Pass sort_categories=True to sort them instead.
The function treats ordered categoricals strictly. If any input is ordered, all inputs must be ordered with the same categories in the same order. Otherwise it raises TypeError. Pass ignore_order=True to drop the ordering and get an unordered result.
Merging on a categorical key
DataFrame.merge follows the same rule as concat. If the key columns on both sides have identical categorical dtypes, the key stays categorical in the result. If the dtypes differ, the key becomes object. Cast both key columns to a shared dtype before you merge, and check result.dtypes afterward.
A quick check after combining
Make this a habit whenever data from different sources is combined:
- Print
combined.dtype. If it saysobject, the categories didn't match. - Compare
combined.isna().sum()with the inputs. A shared dtype that was too narrow turns unexpected values intoNaN. - Look at
combined.cat.categoriesto confirm the order is what you intended, especially for ordered data.
Exercise
You load two monthly files. In one, the "plan" column has categories ["basic", "pro"]. In the other, it has ["pro", "team"]. Calling pd.concat on the two columns gives dtype object. Name two ways to keep a categorical result, and say when you would choose each.
Show answer
Cast both columns to one CategoricalDtype such as pd.CategoricalDtype(["basic", "pro", "team"]) before concatenating. Choose this when you know the full list, because it fixes the order and turns unexpected values into NaN. Alternatively, call pd.Series(union_categoricals([col1, col2])). Choose this when the categories are only known from the data, because it builds the union automatically.