After an upgrade to pandas 3.0, a sales report grouped by a categorical T-shirt size column no longer shows the XL row with zero sales; why, and how do you restore it?
answer
- a changed groupby default
- unused categories versus observed values
- the observed keyword
- zero for sum, NaN for mean
basics
~20 sIn pandas 3.0 groupby defaults to observed=True, so a categorical grouper yields only the categories present in the data. Pass observed=False to get a row for every category, XL included, with 0 for sum, count and size and NaN for mean.
solid answer
~40 sThe `observed` keyword only matters for categorical groupers. pandas 2.x defaulted to `observed=False`, which produced a group for **every category**, used or not; it was deprecated in 2.1, and in pandas 3.0 the default is `observed=True`, so only categories that appear in the data become groups. The size column's dtype still lists XL, but no row has it, so XL vanishes. I restore it with `df.groupby('size', observed=False)['qty'].sum()`, which gives XL a 0; `mean` gives NaN instead. Alternatively I keep the default and `reindex(size_dtype.categories, fill_value=0)`. With several categorical keys, `observed=False` builds every combination of categories, which can explode the result, so I use it deliberately.
code
python · 16 linesimport pandas as pd
size = pd.CategoricalDtype(["S", "M", "L", "XL"], ordered=True)
orders = pd.DataFrame({
"size": pd.Series(["M", "S", "M", "L", "S"], dtype=size),
"qty": [2, 1, 3, 1, 4],
})
default = orders.groupby("size")["qty"].sum()
print(default.to_dict())
full = orders.groupby("size", observed=False)["qty"].sum()
print(full.to_dict())
print(orders.groupby("size", observed=False)["qty"].mean().to_dict())
print(default.reindex(size.categories, fill_value=0).to_dict())go deeper
Recall that a categorical can list values no row holds, and that pandas 3.0 groupby shows only the values present unless you pass observed=False.
Explain what each aggregation returns for an unused category, why the result's CategoricalIndex still knows every category, and how reindex with fill_value restores rows.
Diagnose the upgrade regression quickly, pass observed explicitly on every categorical groupby, and watch for the combination blow-up with several categorical keys.
Set a team rule that categorical groupbys always state observed, so report shapes stay a decision that survives version upgrades.
## What `observed` controls A pandas **categorical** column carries a fixed list of **categories**, and that list can include values no row holds: a T-shirt size dtype `['S', 'M', 'L', 'XL']` on a week with no XL orders, or a frame filtered down to two regions whose categorical still lists all five. Those are **unused** (unobserved) categories. `DataFrame.groupby` and `Series.groupby` take an `observed` keyword that only applies when a grouper is categorical: - `observed=True` - one group per category value that actually appears in the data; - `observed=False` - one group per category in the dtype, whether or not any row has it. ## What changed in pandas 3.0 | Release | Default | Effect on a categorical grouper | |---|---|---| | pandas 2.0 and earlier | `observed=False` | every category becomes a group | | pandas 2.1 to 2.x | `observed=False`, with a deprecation warning when relying on it | same, plus the warning | | pandas 3.0 | `observed=True` | only categories present in the data | A report that relied on the old default to print a zero row for XL silently loses that row after the upgrade. Nothing raises, because both results are legitimate; the report is just shorter. ## Getting the unused rows back There are two clean fixes: 1. **Say what you mean in the call.** `df.groupby('size', observed=False)['qty'].sum()` returns a row for every category in the dtype. This is the right fix when the report must list the full scale. 2. **Keep the default and reindex.** With `observed=True` the result's index is a `CategoricalIndex` whose dtype still lists every category, so `result.reindex(size_dtype.categories, fill_value=0)` adds the missing sizes. Without `fill_value` they come back as NaN. What an unused category gets with `observed=False` depends on the aggregation: | Aggregation | Value for an unused category | |---|---| | `sum`, `count`, `size` | `0` | | `mean`, `median`, `min`, `max` | NaN | | `prod` | `1` (pandas 3.0) | | `any` / `all` | `False` / `True` (pandas 3.0) | The last two rows are also 3.0 changes: pandas 2.x returned NA for `prod`, `any` and `all` on unobserved groups, while `sum` already gave 0. In the same release, `groupby(...).apply` and `agg` with several groupers started passing the unobserved groups to the user function, as a single grouper already did. ## The traps on the other side `observed=False` is not free: - **Combinations explode.** With several groupers, `observed=False` produces the product of their values: grouping by a 4-size and a 50-store categorical yields 200 groups even if only 30 combinations occur. - **Filtering does not remove categories.** After `df[df['size'] != 'L']`, the size dtype still lists L, so `observed=False` prints an L row with zero sales. Run `s.cat.remove_unused_categories()` when the reduced set is what you want. - **Results can turn float.** Aggregations that yield NaN for unused groups, such as `mean` or `max`, return float columns, which matters downstream if a column was expected to stay integer. ## A related default that did not change `Series.value_counts()` on a categorical always lists every category, with a count of `0` for unused ones; it has no `observed` keyword and the 3.0 change does not touch it. That is often the simplest way to get a full-scale frequency table. ## Order of the groups With the default `sort=True`, groups from a categorical come out in **category order**, not alphabetical order, so a size report lists S, M, L, XL when the dtype declares that order. With `sort=False`, groups appear in order of first appearance, and with `observed=False` the unused categories follow them. ## How to answer in an interview State the mechanism (a categorical's dtype can list values no row holds), the 3.0 default change, the two fixes, and the cost of `observed=False` with several keys. Then say which you would choose: an explicit `observed=` argument on every categorical groupby, so the code reads the same on any pandas version and the report's shape is a decision rather than a default.
- Does observed affect grouping by a plain str column?No. A str or object column has no list of possible values beyond what it holds, so every group is observed by definition. The keyword only changes results when at least one grouper is categorical, which is why the upgrade surprise hits only reports built on categorical columns.
- Your observed=False report grouped by size and store suddenly has thousands of empty rows. What happened?With several categorical groupers, `observed=False` produces every combination of their categories, not just the pairs that occur. A store categorical with many unused stores, perhaps left over after filtering, multiplies the rows. Use `observed=True` and reindex only the dimension that must be complete, or drop stale categories with `remove_unused_categories` first.
- pandas 3.0 groupby still shows every category unless observed=True is passed
- observed=False gives unused categories a NaN for sum and count
- Filtering out all L rows also removes L from the column's categories
- The observed keyword changes how a plain str column is grouped
- value_counts on a categorical follows groupby's observed default
pandas 2.x defaulted groupby to observed=False (deprecated since 2.1); pandas 3.0 defaults to observed=True.