Sub topic 10
Combining categoricals from different sources
This chapter assumes you know how a categorical stores categories and integer codes, how to read .cat.categories, and how to use pd.concat and pd.merge on plain columns. It covers what happens when two categorical columns that were built separately are stacked or joined. By default pandas often gives up and returns object dtype, which discards the memory and speed benefits.
Why combining is a problem
A categorical column carries its own set of categories and integer codes that point into that set. Two columns that both look like category can have different category sets, so code 0 can mean "green" in one column and "blue" in another. Stacking them directly would make the codes meaningless.
pandas therefore applies a simple rule. If two categorical columns have exactly the same dtype, it keeps the categorical dtype. The dtype includes the categories, their order, and the ordered flag. If any of these differ, pandas converts the result to object.
import pandas as pd
a = pd.Series(["red", "green"], dtype="category")
b = pd.Series(["blue", "red"], dtype="category")
print(a.cat.categories.tolist()) # ['green', 'red']
print(b.cat.categories.tolist()) # ['blue', 'red']
combined = pd.concat([a, b], ignore_index=True)
print(combined.dtype) # objectThe data is correct, since the values are still the right strings. The column is now stored as one Python string per row, and .cat no longer works on it.
Decision overview
Approach 1: a shared CategoricalDtype
The most reliable fix is to define one CategoricalDtype and apply it to every source. Once the dtypes are equal, concat keeps category.
import pandas as pd
shared = pd.CategoricalDtype(["green", "red", "blue"])
a = pd.Series(["red", "green"], dtype=shared)
b = pd.Series(["blue", "red"], dtype=shared)
combined = pd.concat([a, b], ignore_index=True)
print(combined.dtype == shared) # True
print(combined.tolist()) # ['red', 'green', 'blue', 'red']Pass the shared dtype at the point of creation, for example in read_csv(dtype={"color": shared}) or in astype. The result is never converted to object and back.
Converting columns that already exist
If a column is already categorical with different categories, astype(shared) re-maps it. Values that are not in the new category list become missing.
import pandas as pd
shared = pd.CategoricalDtype(["green", "red", "blue"])
old = pd.Series(["red", "green", "purple"], dtype="category")
fixed = old.astype(shared)
print(fixed.tolist()) # ['red', 'green', nan]
print(fixed.dtype == shared)purple was not listed in shared, so it turned into NaN. This is a data loss that happens quietly. Before converting, check for values you would lose:
import pandas as pd
shared = pd.CategoricalDtype(["green", "red", "blue"])
old = pd.Series(["red", "green", "purple"], dtype="category")
unknown = old[~old.isin(shared.categories) & old.notna()]
print(unknown.tolist()) # ['purple']Approach 2: union_categoricals
When you do not know the full category list in advance, union_categoricals computes it for you. It lives in pandas.api.types and returns a Categorical, not a Series.
import pandas as pd
from pandas.api.types import union_categoricals
a = pd.Series(["red", "green"], dtype="category")
b = pd.Series(["blue", "red"], dtype="category")
u = union_categoricals([a, b])
print(type(u).__name__) # Categorical
print(u.categories.tolist()) # ['green', 'red', 'blue']
print(list(u)) # ['red', 'green', 'blue', 'red']The resulting categories are in order of first appearance across the inputs, with duplicates removed. Pass sort_categories=True to sort them instead.
import pandas as pd
from pandas.api.types import union_categoricals
a = pd.Series(["red", "green"], dtype="category")
b = pd.Series(["blue", "red"], dtype="category")
u = union_categoricals([a, b], sort_categories=True)
print(u.categories.tolist()) # ['blue', 'green', 'red']Using the union as a shared dtype
A common pattern for many files or chunks is a two-pass approach. First, compute the union. Second, cast every piece to the same dtype, so ordinary concat works.
import pandas as pd
from pandas.api.types import union_categoricals
part1 = pd.DataFrame({"color": pd.Categorical(["red", "green"]), "n": [1, 2]})
part2 = pd.DataFrame({"color": pd.Categorical(["blue", "red"]), "n": [3, 4]})
parts = [part1, part2]
cats = union_categoricals([p["color"] for p in parts]).categories
shared = pd.CategoricalDtype(cats)
parts = [p.astype({"color": shared}) for p in parts]
df = pd.concat(parts, ignore_index=True)
print(df["color"].dtype == shared) # True
print(df["color"].cat.categories.tolist())This is a typical situation when files are read one at a time with dtype="category". Each file infers its own categories, so a plain concat at the end would produce object.
Ordered categoricals
Ordered categoricals are stricter, because combining two different orders has no meaningful answer. For union_categoricals, ordered inputs must have identical categories in the identical order. Otherwise it raises TypeError.
import pandas as pd
from pandas.api.types import union_categoricals
low_first = pd.Categorical(["a", "b"], categories=["a", "b"], ordered=True)
high_first = pd.Categorical(["a", "b"], categories=["b", "a"], ordered=True)
try:
union_categoricals([low_first, high_first])
except TypeError as err:
print("TypeError:", err)
# Explicitly drop the ordering if that is acceptable
u = union_categoricals([low_first, high_first], ignore_order=True)
print(u.ordered) # Falseignore_order=True returns an unordered result. Use it only if the order is not needed afterward. If it is needed, define one ordered CategoricalDtype and cast both sides to it, as in Approach 1.
With plain pd.concat, ordered columns with different category orders also fall back to object.
Merging on categorical keys
pd.merge follows the same rule for join keys. If both key columns have equal categorical dtypes, the result key stays categorical. If the dtypes differ, the result key is object.
import pandas as pd
shared = pd.CategoricalDtype(["bronze", "silver", "gold"])
left = pd.DataFrame({
"tier": pd.Series(["gold", "bronze"], dtype=shared),
"customers": [10, 40],
})
right = pd.DataFrame({
"tier": pd.Series(["bronze", "gold", "silver"], dtype=shared),
"discount": [0.0, 0.2, 0.1],
})
merged = left.merge(right, on="tier")
print(merged["tier"].dtype == shared) # True
print(merged)If left and right had inferred their own categories, the merge would still produce correct matches, but merged["tier"] would be object. Joining a categorical column against a plain object column behaves the same way.
Other operations to watch
| Operation | Result when categories differ |
|---|---|
| `pd.concat` of Series or DataFrame columns | `object` |
| `pd.merge` on a categorical key | `object` key column |
| `union_categoricals` | `Categorical` with the union of categories |
| Assigning a value not in the categories | `TypeError` or `ValueError` (see the previous chapter on managing categories) |
| `Series.where` or `fillna` with a new value | Error unless the value is already a category |
Two further details are worth knowing:
- Concatenating a categorical column with an
objectorstringcolumn also producesobject. The categorical is not given priority. - The order of categories matters for equality.
["a", "b"]and["b", "a"]are different dtypes when compared with==, even for unordered categoricals. Unordered dtypes with the same categories in a different order are treated as equal byCategoricalDtype.__eq__, but you should not rely on this when the code positions matter. Build both from the same list to be safe.
Practical checklist
- Decide the category list once, in one place. Store it as a module-level
CategoricalDtype. - Apply that dtype when reading data, not after combining.
- If you must discover categories, use
union_categoricalson the pieces, then cast. - Count missing values before and after casting, to catch values that fell outside the list.
- After combining, assert the dtype, for example
assert df["color"].dtype == shared.
Exercises
Exercise
You read two CSV files with dtype="category" for the column status. File 1 contains "open" and "closed". File 2 contains "closed" and "pending". What dtype does pd.concat([df1, df2])["status"] have, and what is one way to keep it categorical?
Show answer
It is object, because the two columns have different categories. One fix is to build shared = pd.CategoricalDtype(["open", "closed", "pending"]) and read or cast both files with it before concatenating. Another is to compute the categories with union_categoricals and cast both pieces to a CategoricalDtype made from them.
Exercise
union_categoricals raises a TypeError for two ordered categoricals with the categories ["low", "high"] and ["high", "low"]. Name two ways to handle this.
Show answer
Pass ignore_order=True to get an unordered result, if the order is no longer needed. Or cast both inputs to one ordered CategoricalDtype with the intended order, then combine them.