Sub topic 9
Groupby and unobserved categories
This chapter assumes you can run a basic groupby, and that you know a categorical column has a fixed list of categories that can include values the data never uses. The question here is what groupby does with a category that has no rows.
Observed and unobserved categories
An observed category appears at least once in the column. An unobserved category is in the dtype's category list but has no rows. Categoricals keep unobserved categories on purpose, because the category list is part of the dtype and not a summary of the data.
Grouping on a categorical key forces a choice: should the result contain a row for each category, or only for categories that occur? The observed argument controls this.
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())With observed=False, the result has three rows, and mid shows a sum of 0. With observed=True, the result has two rows and mid is missing.
What empty groups return
An unobserved group gets the result of an aggregation over zero rows, and that result depends on the function.
| Aggregation | Result for an empty group |
|---|---|
| `sum` | 0 |
| `size`, `count` | 0 |
| `mean`, `min`, `max` | NaN |
You can check the mean case yourself:
print(df.groupby("level", observed=False)["value"].mean())The mid row is NaN. Because of the NaN, an integer result can become a float column.
Why the default matters
Pandas 2.1 deprecated the old default, observed=False. A categorical groupby that doesn't set observed raises a FutureWarning. In pandas 3.0 the default is observed=True. The same code can therefore return different shapes on different pandas versions. Pass observed explicitly whenever the key is categorical.
Use observed=False when the output feeds a report with a fixed layout, a join against a complete list, or a chart where missing bars would mislead. Use observed=True for exploratory work and large results.
The cost with several keys
The cost grows with more than one categorical key. With observed=False, pandas builds every combination of categories, whether or not that combination occurs.
color = pd.CategoricalDtype(["red", "blue"])
df2 = pd.DataFrame({
"level": pd.Series(["low", "high"], dtype=level),
"color": pd.Series(["red", "blue"], dtype=color),
"value": [1, 2],
})
print(df2.groupby(["level", "color"], observed=False).size())
print(df2.groupby(["level", "color"], observed=True).size())The first call returns 6 rows (3 levels times 2 colors), and four of them are 0. The second returns 2 rows. With columns that have hundreds of categories each, the product can use a lot of memory. Prefer observed=True there, and reindex afterward only if you need the full grid.
Related behavior
pivot_tablehas its ownobservedargument. It follows the same rules and the same version change.value_counts()on a categorical Series lists unobserved categories with a count of 0.- If the key is not categorical,
observedhas no effect. dropnais a separate setting. It controls whether missing keys form a group, not whether unused categories do.
Getting a full set of groups later
If you chose observed=True and later need every category, restore the missing ones with reindex:
result = df.groupby("level", observed=True)["value"].sum()
full = result.reindex(level.categories, fill_value=0)
print(full)This gives the same table as observed=False with sum. It works for a single key, and you choose the fill value yourself.
Exercise
A DataFrame has a categorical column "status" with categories ["new", "active", "closed"], and no row has the value "active". You run df.groupby("status", observed=False)["amount"].mean(). What does the "active" row contain, and what would change if you used observed=True?
Show answer
The "active" row contains NaN, because the mean of zero rows is undefined. With observed=True, the "active" row would not appear in the result at all, so the result has only "new" and "closed".