Sub topic 9
Groupby and unobserved categories
This chapter explains what groupby does when the grouping key is a categorical column. It covers the observed argument, the cases where the choice changes results, and how to pick a setting on purpose. It assumes you can use groupby and value_counts, and that you know a categorical stores a fixed list of categories plus integer codes.
Why categorical keys behave differently
With an object or integer key, groupby can only form groups for values that occur in the data. A categorical key also carries a declared list of categories, and that list can include values that never occur. A category with no rows is called an unobserved category.
pandas has to decide whether an unobserved category gets a row in the result. The observed argument controls that decision:
observed=Falsekeeps a result row for every category, including unobserved ones.observed=Truekeeps only categories that occur in the data.
The default has changed over time. Older pandas versions defaulted to False. From pandas 2.1, leaving observed unset with a categorical key raises a FutureWarning. In pandas 3.0 the default became True. Check your installed version with pd.__version__. Code that sets observed explicitly behaves the same on every version.
A first comparison
This example uses a three-category column in which "mid" never appears.
import pandas as pd
level = pd.CategoricalDtype(["low", "mid", "high"])
df = pd.DataFrame({
"level": pd.Series(["low", "low", "high"], dtype=level),
"value": [1, 2, 3],
})
print(df.groupby("level", observed=False)["value"].sum())
print(df.groupby("level", observed=True)["value"].sum())The first call returns three rows: low is 3, mid is 0 and high is 3. The second call returns two rows, low and high, and mid is absent.
Both results list the groups in category order (low, mid, high), not alphabetical order. This holds for either setting of observed. It is one reason categorical keys are useful for reports.
What an unobserved group contains
An unobserved group has no rows, so each aggregation returns its "empty" result. These results differ by function.
| Aggregation | Result for an unobserved category |
|---|---|
| `sum()` | `0` |
| `count()` | `0` |
| `size()` | `0` |
| `mean()`, `median()`, `std()` | `NaN` |
| `min()`, `max()`, `first()`, `last()` | `NaN` |
Here is the effect on a mean and a size:
import pandas as pd
level = pd.CategoricalDtype(["low", "mid", "high"])
df = pd.DataFrame({
"level": pd.Series(["low", "low", "high"], dtype=level),
"value": [1, 2, 3],
})
g = df.groupby("level", observed=False)
print(g["value"].mean()) # low 1.5, mid NaN, high 3.0
print(g.size()) # low 2, mid 0, high 1A zero from sum() and a NaN from mean() can mislead a reader. A sum of 0 looks like "we measured and got nothing". It actually means "no rows existed". If the distinction matters, report size() next to the aggregate, or use observed=True and handle missing categories separately.
The mean() column also turns into floats. An integer sum() stays integer because 0 is a valid integer, but a column containing NaN cannot stay integer.
Several categorical keys: the Cartesian product
The surprising case appears when you group by more than one categorical key. With observed=False, pandas builds every combination of the categories, which is the Cartesian product.
import pandas as pd
df = pd.DataFrame({
"size": pd.Categorical(["S", "L", "S"], categories=["S", "M", "L"]),
"color": pd.Categorical(["red", "red", "blue"], categories=["red", "blue"]),
"sales": [10, 20, 30],
})
full = df.groupby(["size", "color"], observed=False)["sales"].sum()
seen = df.groupby(["size", "color"], observed=True)["sales"].sum()
print(len(full)) # 6 (3 sizes x 2 colors)
print(len(seen)) # 3
print(full)
print(seen)The full result has six rows: (S, red) is 10, (S, blue) is 30, (M, red) and (M, blue) are 0, (L, red) is 20 and (L, blue) is 0. The observed result has only the three combinations that occur in the data.
Note that ("M", "red") is unobserved even though both "M" and "red" are valid categories. "M" never appears and "red" does, but the pair never appears together. observed=True removes every combination that has no rows, not just unused single categories.
The row count is the product of the category counts, so it grows quickly:
sizes = 1_000 # categories in key A
shops = 5_000 # categories in key B
print(sizes * shops) # 5000000 result rows, even if only 20,000 pairs occurWith high-cardinality categorical keys, observed=False can produce millions of mostly empty rows and use a lot of memory. Large categorical keys are common, such as product IDs and user IDs stored as categoricals to save memory. In that case use observed=True.
Choosing a setting
The question to ask is whether absent categories are meaningful for the person reading the result.
Instead of the placeholder above, here is the decision flow as a proper diagram.
Use observed=False when:
- The result is a report or chart where a missing bucket would look like an error. Examples are survey answers, star ratings and days of the week.
- You want a fixed result shape across runs, so downstream code can rely on every category having a row.
- You have one or two keys with few categories.
Use observed=True when:
- The key has many categories, or you group by several categorical keys.
- You only care about groups that have data.
- You want the same behavior on pandas 2.x and 3.x without surprises.
Getting a full table without the full product
If you need the zero rows for one key but not for the whole product, group with observed=True and then reindex on the category list you care about.
import pandas as pd
level = pd.CategoricalDtype(["low", "mid", "high"])
df = pd.DataFrame({
"level": pd.Series(["low", "low", "high"], dtype=level),
"value": [1, 2, 3],
})
result = df.groupby("level", observed=True)["value"].sum()
result = result.reindex(level.categories, fill_value=0)
print(result) # low 3, mid 0, high 3This gives you control over the fill value. You could fill with 0 for counts and sums, and leave NaN for means.
Other tools that follow the same rule
Several pandas functions that group internally have their own observed handling.
pivot_tablehas anobservedargument that works like thegroupbyone. Cross-tabulating two categorical columns withobserved=Falsecreates a full grid.value_counts()on a categorical Series always includes unobserved categories, with a count of 0. It has noobservedargument, so filter withs.value_counts()[lambda c: c > 0]if you want to drop them.df.groupby(...).value_counts()andunstack()on categorical indexes can also expand to all categories.
If you need an unordered, alphabetical result from a categorical key, convert it first with astype(object). This drops category order and the unobserved categories at the same time, so use it only when you do not need either.
Missing values as keys
A NaN in a categorical column is not a category. By default (dropna=True) groupby drops rows with a missing key. To keep them as their own group, pass dropna=False:
import pandas as pd
s = pd.Series(["a", None, "a", "b"], dtype="category")
df = pd.DataFrame({"key": s, "v": [1, 2, 3, 4]})
print(df.groupby("key", observed=True)["v"].sum()) # a 4, b 4
print(df.groupby("key", observed=True, dropna=False)["v"].sum()) # a 4, b 4, NaN 2The observed setting does not affect this. A missing value is a separate matter from an unused category.
Common errors
- Surprise zero rows. A report shows categories you thought were gone. Check
df["col"].cat.categoriesand callremove_unused_categories()if the extra categories are leftovers from filtering. Filtering rows does not shrink the category list. - Memory blow-up. A multi-key groupby with
observed=Falseruns out of memory or is slow. Switch toobserved=True. - Version drift. A script gives different row counts after upgrading pandas because it relied on the default. Always pass
observedexplicitly. - Misread
NaNand0. Treat zeros fromsum()as "no data", not "measured zero", when the group is unobserved.
Exercise
A DataFrame has a categorical column grade with categories ["A", "B", "C", "D"] and the data contains only "A" and "C". You run df.groupby("grade", observed=False)["score"].mean() and then df.groupby("grade", observed=True)["score"].mean(). How many rows does each result have, and what are the values for "B" and "D" in the first one? Then, for two categorical keys with 50 and 200 categories, how many rows can observed=False return?
Show answer
The first result has 4 rows and the second has 2 rows ("A" and "C"). In the first result, "B" and "D" are NaN because the mean of an empty group is undefined. With two keys of 50 and 200 categories, observed=False can return 50 x 200 = 10,000 rows, even if far fewer combinations occur in the data.
Exercise
You group sales by a categorical region column with observed=True, but the report must always show all five regions, with 0 for regions that have no sales. How do you produce that without using observed=False?
Show answer
Run sales.groupby("region", observed=True)["amount"].sum() and then call .reindex(df["region"].cat.categories, fill_value=0) on the result. The reindex adds a row for each category and fills the missing ones with 0.