In pandas, per-customer totals from `orders.groupby('customer_id')['amount'].sum()` add up to less than `orders['amount'].sum()`; why, and how do you fix it?
answer
- look at the key, not the values
- a default on groupby itself
- guest checkouts with no ID
- a missing value in any key
basics
~20 sgroupby defaults to dropna=True, so rows whose customer_id is missing belong to no group and their amounts vanish from the totals without a warning. Pass dropna=False to keep a NaN group, or fill the key first, for example with 'guest'.
solid answer
~40 sThe amounts are not the cause: `sum` skips missing amounts in both totals alike. The key is. `DataFrame.groupby` has `dropna=True` by default, which leaves rows whose group key is missing out of every group, so guest orders with no `customer_id` disappear without a warning. With several keys, a missing value in any one of them drops the row. `dropna=False` keeps those rows as a group labelled NaN, placed last when the keys are sorted, and `orders.groupby(orders['customer_id'].fillna('guest'))` gives them a readable label instead. In a pipeline, reconcile the grouped total with the source total, or count `orders['customer_id'].isna()` before grouping, because the default fails silently.
code
python · 11 linesimport pandas as pd
orders = pd.DataFrame({
"customer_id": ["c2", None, "c1", "c1", "c2", None],
"amount": [20.0, 35.0, 5.0, 50.0, 15.0, 10.0],
})
print(orders["amount"].sum())
print(orders.groupby("customer_id")["amount"].sum().sum())
print(orders.groupby("customer_id", dropna=False)["amount"].sum())
print(orders.groupby(orders["customer_id"].fillna("guest"))["amount"].sum())go deeper
Recall that groupby leaves out rows whose key is missing unless dropna=False is passed.
Explain the difference between missing keys and missing values, and why a second key with gaps can lower a total that was right before.
Show the diagnosis path, isna count on the key, sizes against len, totals against source, and choose between dropna=False, fillna and an explicit filter for the data at hand.
Make reconciliation checks a standard part of shared aggregation code, so silently excluded rows surface as a failing assertion rather than a wrong dashboard.
## The symptom A per-customer revenue table is built with `orders.groupby('customer_id')['amount'].sum()`, and its total is lower than `orders['amount'].sum()`. Nothing raised, nothing warned, and every individual number looks plausible. This is one of the most common silent losses in pandas reporting. ## Why: `dropna=True` on `groupby` - `DataFrame.groupby` and `Series.groupby` take a **`dropna`** argument whose default is **`True`**. - With `dropna=True`, a row whose **group key** is missing (NaN, `None`, `pd.NA`, NaT) is **not assigned to any group**. It is not an error and not a group of its own; it simply takes no part in the result. - Missing **values** are a different matter. `sum` skips missing amounts by default, both in the grouped total and in `orders['amount'].sum()`, so they cannot explain a difference between the two. - `size()` shows the same loss from another angle: the group sizes add up to fewer rows than the frame has. Typical sources of missing keys: guest checkouts, a failed join that left IDs empty, a lookup column read from a file with blanks. ## Three fixes | Approach | Result for the missing-key rows | When to use it | |---|---|---| | `groupby('customer_id', dropna=False)` | one group labelled NaN | you want to see them, labelled as missing | | `groupby(orders['customer_id'].fillna('guest'))` | one group labelled `guest` | the report needs a readable label | | Filter first, then group | excluded on purpose | the rows are invalid and should be gone, explicitly | With `dropna=False` and the default `sort=True`, the NaN group comes last, after the sorted real keys. Because NaN is not equal to itself, find that group with `result.index.isna()` rather than an equality test. ## Several keys With a list of keys, the rule applies per row across all of them: 1. Group by `['customer_id', 'channel']` with the default `dropna=True`. 2. Any row with a missing `customer_id` **or** a missing `channel` is excluded; the key does not need to be missing everywhere. 3. With `dropna=False`, those rows are kept, and NaN appears as a label in whichever level was missing, giving entries such as `('c1', NaN)`. So adding a second key can lower a total that was correct with one key, if the new column has gaps. ## Guarding a pipeline Because the default fails silently, a production transform should make the decision visible: 1. **Measure** before grouping: `orders['customer_id'].isna().sum()` tells you how many rows are at risk. 2. **Decide** the policy explicitly: keep (`dropna=False`), relabel (`fillna`), or drop with a logged count. 3. **Reconcile** after grouping: assert that the grouped total equals the source total, or that the group sizes add up to `len(orders)`, whenever rows are supposed to be kept. These checks are cheap, and they catch the same problem when an upstream change starts producing missing keys months later. ## Other key forms follow the same rule The exclusion is about the key's values, not how the key was spelled: - A **Series** passed as the key, such as `orders['email'].str.lower()`, drops rows where that Series is missing, exactly like a column name. - A key computed by `fillna` before grouping can never be missing, which is why relabelling is the most explicit fix. - **`pd.Grouper`** has its own `dropna` parameter, also `True` by default. When it bins by `freq`, a row with a NaT date falls outside every bin even with `dropna=False`, so fill or filter missing dates first. In an interview, the strongest answer names the cause in one sentence, then shows the check that would have caught it: compare the grouped total with the source total, and count missing keys before grouping. ## Other `dropna` arguments are separate Several pandas methods have a parameter called `dropna`, and they mean different things: - `groupby(dropna=...)` decides whether rows with a missing **key** form a group. - `nunique(dropna=...)` decides whether missing **values** count as a distinct value inside each group. - `DataFrame.dropna()` removes rows or columns with missing values from the frame itself; filling and dropping data is its own lesson. Setting one never changes the others, so `dropna=False` on `groupby` does nothing about missing amounts, and `dropna()` on the frame before grouping would remove rows rather than keep them. ## A related but different loss Categorical keys have a separate argument, `observed`, that decides whether categories with no rows appear in the result. That governs groups with no rows, not rows with no group, and it cannot make a total disagree with the source, because unobserved categories hold no amounts.
- Where does the NaN group appear with `dropna=False`, and how do you select it?With the default `sort=True` the NaN group comes last, after the sorted real keys. NaN does not compare equal to itself, so select it with a mask on the index, `result[result.index.isna()]`, rather than an equality test against NaN.
- With keys `['customer_id', 'channel']`, which rows does the default exclude?Every row with a missing value in either key, not only rows missing both. With `dropna=False` those rows are kept, and NaN appears in whichever level was missing, so totals reconcile again.
- How can `size()` confirm the loss without looking at amounts?Add up the group sizes and compare with `len(orders)`. With the default `dropna=True` the rows with a missing key belong to no group, so the sum of `size()` falls short by exactly that number of rows.
- groupby keeps rows with a missing key in a NaN group by default.
- The totals differ because sum() skips missing amounts.
- pandas warns when groupby leaves rows with a missing key out.
- Only a missing value in the first key excludes the row.
- groupby(dropna=False) changes how missing amounts are summed.