Sub topic 8
Missing keys and group ordering
This chapter covers two defaults that change a groupby result without raising an error. The first is that rows with a missing group key are dropped. The second is that groups come back sorted by key. It assumes you can build a DataFrame, select columns, and run a basic groupby(...).sum(). It also assumes you know that NaN is pandas' marker for a missing value.
Missing keys are dropped by default
A group key is the value in the grouping column for each row. If that value is missing (NaN, None, or NaT), pandas has no group to put the row in. By default it leaves the row out of the result.
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: int64The row with v = 2 is gone. No warning is raised. The group totals now add up to 4, while the column total is 6.
This is a common source of "my totals don't match" bugs. A quick reconciliation check catches it:
import pandas as pd
keys = pd.DataFrame({"k": ["a", None, "a"], "v": [1, 2, 3]})
grouped_total = keys.groupby("k")["v"].sum().sum()
print(keys["v"].sum() - grouped_total) # 2
print(keys["k"].isna().sum()) # 1 row has a missing keyKeeping missing keys with dropna=False
Pass dropna=False to keep missing keys as their own group.
import pandas as pd
keys = pd.DataFrame({"k": ["a", None, "a"], "v": [1, 2, 3]})
print(keys.groupby("k", dropna=False)["v"].sum())
# k
# a 4
# NaN 2
# Name: v, dtype: int64The missing group is labeled NaN in the index. Its totals now include the rows that were previously dropped.
With several keys, a row is dropped by default if any key is missing. With dropna=False, each distinct combination is kept, including combinations where only one key is missing.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"region": ["N", "N", np.nan, "S"],
"product": ["A", np.nan, "A", "A"],
"units": [1, 2, 3, 4],
})
print(df.groupby(["region", "product"], as_index=False)["units"].sum())
# region product units
# 0 N A 1
# 1 S A 4
print(df.groupby(["region", "product"], dropna=False, as_index=False)["units"].sum())
# region product units
# 0 N A 1
# 1 N NaN 2
# 2 S A 4
# 3 NaN A 3With the default, two of the four rows disappear. With dropna=False, all four rows are counted. The NaN group is listed last.
Choosing between dropping and keeping
The right choice depends on what a missing key means in your data.
| Situation | Setting | Reason |
|---|---|---|
| Missing key means "not applicable" and should not appear in reports | `dropna=True` (default) | The report only covers known categories |
| Missing key means "unknown" and the rows still carry real values | `dropna=False` | Totals reconcile with the source table |
| You are auditing data quality | `dropna=False` | The size of the unknown group is itself a finding |
| You will later merge group results back by key | Fill the key first, then group | Merging on `NaN` keys is awkward |
Filling the key before grouping is often the clearest approach, because the label shows up in plain text:
import pandas as pd
keys = pd.DataFrame({"k": ["a", None, "a"], "v": [1, 2, 3]})
filled = keys.assign(k=keys["k"].fillna("unknown"))
print(filled.groupby("k")["v"].sum())
# k
# a 4
# unknown 2
# Name: v, dtype: int64Group ordering and sort
By default, groupby sorts the groups by key. The result index is in ascending key order, not in the order the groups first appear in the data. This is the sort=True default.
import pandas as pd
orders = pd.DataFrame({
"city": ["Paris", "Austin", "Paris", "Cairo", "Austin"],
"amount": [10, 20, 30, 45, 5],
})
print(orders.groupby("city")["amount"].sum())
# city
# Austin 25
# Cairo 45
# Paris 40
# Name: amount, dtype: int64Setting sort=False returns the groups in the order each key first appears in the data.
import pandas as pd
orders = pd.DataFrame({
"city": ["Paris", "Austin", "Paris", "Cairo", "Austin"],
"amount": [10, 20, 30, 45, 5],
})
print(orders.groupby("city", sort=False)["amount"].sum())
# city
# Paris 40
# Austin 25
# Cairo 45
# Name: amount, dtype: int64Paris appears first in the data, so it comes first in the output.
What sort does and does not control
- It orders groups by key, not by value. To rank groups by their totals, sort the result:
orders.groupby("city")["amount"].sum().sort_values(ascending=False). Settingsort=Falsedoes not rank anything. - It does not reorder rows inside a group. Within each group, rows keep their original order. This matters for
first,last,head, andnth, which depend on row order.sort=Falsedoes not change which rowfirstreturns. - It does not affect
transform. Atransformresult is aligned to the original rows, so the order of groups cannot change it. Only results that have one row per group depend onsort. - It follows category order for categorical keys. If the key column has a categorical dtype, groups are ordered by the declared categories rather than alphabetically. A later chapter covers this with the
observedparameter.
Sorting and performance
Sorting group keys costs time that grows with the number of groups. With a few dozen groups the cost is negligible. With millions of distinct keys, sort=False can save measurable time. Use it when you do not need ordered output, or when you plan to sort the result by values anyway.
Do not rely on sort=False as a way to preserve the original data order in a result you later compare against another. The order is "first appearance", which changes if the input rows are shuffled. For a stable, reproducible order, keep sort=True or sort explicitly afterwards.
Putting the two settings together
The two parameters are independent. You can keep missing keys and still control their position.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"k": [np.nan, "b", "a", "b"],
"v": [1, 2, 3, 4],
})
print(df.groupby("k", dropna=False, sort=True)["v"].sum())
# k
# a 3
# b 6
# NaN 1
# Name: v, dtype: int64
print(df.groupby("k", dropna=False, sort=False)["v"].sum())
# k
# NaN 1
# b 6
# a 3
# Name: v, dtype: int64With sort=True the NaN group is placed last. With sort=False it appears where its first row does, which here is the top.
Common errors
- Totals that are too small. The cause is usually dropped missing keys. Compare
df["v"].isna().sum()anddf["k"].isna().sum()to see which column holds the missing values, then reconcile againstdf["v"].sum(). - Assuming output follows input order. Under the default
sort=True, output is in key order. Passsort=Falseif you need first-appearance order. - Expecting
sort=Falseto rank by value. It does not. Usesort_valueson the result. - Treating empty strings as missing. An empty string
""is a real value, so it forms its own group even with the defaultdropna=True. Convert placeholders such as""or"N/A"toNaNfirst if you want them handled as missing.
Exercise
A DataFrame has a column "team" with values ["red", "blue", None, "red", None] and a column "points" with values [3, 5, 2, 4, 1]. What does df.groupby("team", dropna=False, sort=False)["points"].sum() return? Give the index order and the values.
Show answer
The index order is red, blue, NaN, which is the order of first appearance. The values are red = 7 (3 + 4), blue = 5, and NaN = 3 (2 + 1). With the defaults (dropna=True, sort=True) the result would instead be blue = 5, red = 7, with the two rows that have a missing team dropped.
Exercise
You run df.groupby("k")["v"].sum() and the group totals add up to less than df["v"].sum(). Name two things you could check, and one change that would make the totals reconcile.
Show answer
Check df["k"].isna().sum() to see whether rows have a missing key, and check that the values being summed are not themselves missing (df["v"].isna().sum()), since sum skips them. If missing keys are the cause, pass dropna=False to groupby, or fill the key column first with fillna("unknown"). Either way the rows that were dropped become part of a visible group.