Sub topic 8
Missing keys and group ordering
This chapter assumes you can build a DataFrame, select columns, and run a basic groupby(...).sum(). It covers two things that change which groups appear in the result and the order they appear in: missing group keys and the sort parameter.
What happens to rows with a missing key
A group key can be missing (None or NaN). By default, pandas drops those rows from the result. The dropna parameter controls this. Its default is True.
import pandas as pd
keys = pd.DataFrame({"k": ["a", None, "a"], "v": [1, 2, 3]})
print(keys.groupby("k")["v"].sum())
# k
# a 4
# Name: v, dtype: int64
print(keys.groupby("k", dropna=False)["v"].sum())
# k
# a 4
# NaN 2
# Name: v, dtype: int64The row with v = 2 vanishes in the first call without any warning. In the second call it forms its own group, and the group label is NaN.
Multiple keys
With several keys, a row is dropped under the default setting if any one of its keys is missing. A row with region="North" and product=None is excluded, even though its region is valid. With dropna=False, that row is kept in a group such as ("North", NaN).
Missing keys versus missing values
dropna applies only to group keys. Missing values in the column you aggregate are handled by the aggregation itself. sum skips them and count does not count them. The earlier chapter on size and count covers this.
Group ordering
By default, groupby sorts the groups by key, so the result index is in ascending order. The sort parameter controls this, and its default is True. When missing keys are kept with dropna=False, the NaN group is placed last.
df = pd.DataFrame({"k": ["b", "a", "c", "a"], "v": [1, 2, 3, 4]})
print(df.groupby("k")["v"].sum())
# k
# a 6
# b 1
# c 3
# Name: v, dtype: int64
print(df.groupby("k", sort=False)["v"].sum())
# k
# b 1
# a 6
# c 3
# Name: v, dtype: int64With sort=False, the groups appear in the order their keys first show up in the data. Here b comes first, then a, then c.
What sort does not change
- It does not change the values. Every group gets the same total either way.
- It does not reorder rows inside a group. Within each group, rows keep their original order in the source.
- It does not sort by value. To rank groups by their totals, call
sort_valueson the result, for example.sum().sort_values(ascending=False).
When to turn sorting off
Sorting the group keys costs some time, so sort=False can speed up grouping on large data with many groups. Use it when you do not need ordered output, or when first-appearance order is meaningful, such as when the input is already in a deliberate order.
| Parameter | Default | Effect when changed |
|---|---|---|
| `dropna` | `True` | `False` keeps rows with missing keys as a `NaN` group |
| `sort` | `True` | `False` orders groups by first appearance |
Exercise
A DataFrame has columns "city" and "sales". Three rows have a missing city. You run df.groupby("city")["sales"].sum() and the totals add up to less than df["sales"].sum(). What is the cause, and how do you include those rows in the result?
Show answer
By default, dropna=True removes rows whose group key is missing, so the sales from those three rows are left out. Pass dropna=False, as in df.groupby("city", dropna=False)["sales"].sum(), to keep them in a NaN group.