Sub topic 14
Missing values in summaries and groups
This chapter assumes you can build a DataFrame, select columns, and use groupby with agg as shown earlier. It covers how missing values (NaN) change summaries and groups, and how to control that behavior.
Summaries skip missing values by default
Reductions such as sum, mean, min and max have a skipna argument that defaults to True. The units column in the sales table has one missing value, so the results look like this:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
print(df["units"].sum()) # 42.0
print(df["units"].mean()) # 8.4, which is 42 / 5
print(df["units"].sum(skipna=False)) # nan
print(df["units"].count()) # 5
print(len(df)) # 6The mean divides by 5, not 6, because count ignores NaN. describe behaves the same way, so its count row shows 5. Use skipna=False when a missing value should make the whole result unreliable.
Missing values inside groups
groupby aggregations skip NaN in the value columns in the same way. The difference between size and count becomes useful here:
summary = df.groupby("region").agg(
total_units=("units", "sum"),
valid_units=("units", "count"),
orders=("product", "size"),
)
print(summary)size counts all rows in each group, and count counts only the non-missing values. North has orders equal to 2 but valid_units equal to 1. Comparing the two columns shows how much data each total rests on.
An all-missing group has a trap. sum returns 0.0 for it, while mean returns NaN. You can make sum return NaN instead with min_count:
tmp = df.copy()
tmp.loc[tmp["region"] == "North", "units"] = None
print(tmp.groupby("region")["units"].sum())
print(tmp.groupby("region")["units"].sum(min_count=1))The first call reports North as 0.0, which looks like a real total. The second reports NaN, which tells you that no data exists.
Missing group keys
Rows whose group key is missing are dropped by default. This is controlled by dropna on groupby:
keys = df.copy()
keys.loc[3, "region"] = None
print(keys.groupby("region")["units"].sum())
print(keys.groupby("region", dropna=False)["units"].sum())The first result has no row for the missing region, so the 8 units in that row do not appear in any total. The second result adds a NaN group that holds them. The same idea applies to value_counts, which also takes dropna=False if you want to count missing categories.
Missing values when sorting the result
Sorting a summary follows the same rules as sorting any column. NaN goes last unless you pass na_position="first". If you used min_count=1, check that sorted results do not hide empty groups at the bottom.
| Goal | Option |
|---|---|
| Let one missing value ruin a total | `skipna=False` |
| Return `NaN` for an all-missing group | `sum(min_count=1)` |
| Keep rows with a missing group key | `groupby(..., dropna=False)` |
| Count rows including missing values | `size` |
| Count only present values | `count` |
Exercise
A grouped table shows total_units of 0.0 for a region, but you suspect the data is missing, not zero. How can you confirm this, and how can you make the total show NaN?
Show answer
Add a count aggregation (for example ("units", "count")) and check whether it is 0 for that region, while size is greater than 0. To show NaN instead of 0.0, call sum(min_count=1) on the grouped column.