Sub topic 14
Missing values in summaries and groups
This chapter covers how missing values (NaN) change the numbers that reductions, groupby, value_counts and pivot_table produce. It assumes you can build a DataFrame, select columns, and tell a Series from a DataFrame. It also assumes you have read the earlier chapters on describe, groupby and named aggregation.
The data
The examples use the same sales table as the rest of the tutorial. One units value is missing.
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],
})Because units contains None, pandas stores the column as float64, and the gap becomes NaN.
Reductions skip missing values by default
Reductions such as sum, mean, min, max and std ignore NaN. This is controlled by the skipna argument, which defaults to True.
units = df["units"]
print(units.sum()) # 42.0
print(units.mean()) # 8.4
print(units.sum(skipna=False)) # nan
print(units.count(), units.size) # 5 6mean divides by the number of non-missing values, so 42 / 5 = 8.4. It does not divide by the six rows. count() returns the number of non-missing values, while size counts every row. The gap between the two tells you how many values are missing.
describe follows the same rule. Its count row shows 5 for units, and the mean and quartiles come from those five values only.
print(df["units"].describe())Setting skipna=False is useful when a missing value should make the whole result unreliable. The result is then NaN instead of a number that quietly leaves rows out.
Skipping is not the same as treating as zero
Filling gaps with 0 before aggregating gives a different answer from skipping them.
print(df["units"].mean()) # 8.4
print(df["units"].fillna(0).mean()) # 7.0Which one is right depends on what the gap means. If a missing value means "no units were sold", fill it with 0. If it means "we don't know", skipping it is more honest. State your choice, because the two results differ by 1.4 units here.
Missing values inside groups
groupby aggregations also skip NaN in the value columns. In the North group, one of the two rows has no units.
print(df.groupby("region")["units"].sum())
print(df.groupby("region")["units"].mean())
print(df.groupby("region")["units"].count())
print(df.groupby("region").size())The results are:
| region | sum | mean | count | size |
|---|---|---|---|---|
| East | 15.0 | 7.5 | 2 | 2 |
| North | 10.0 | 10.0 | 1 | 2 |
| South | 17.0 | 8.5 | 2 | 2 |
The North mean is 10.0 because it is computed from a single value. The North total of 10.0 looks like a normal two-order total, and nothing in the number reveals the gap.
Showing data quality next to the result
A good habit is to report the count of valid values beside each statistic. Named aggregation makes this easy.
summary = df.groupby("region").agg(
total_units=("units", "sum"),
avg_units=("units", "mean"),
rows=("units", "size"),
valid_units=("units", "count"),
)
print(summary.sort_values("total_units", ascending=False))The output is:
total_units avg_units rows valid_units
region
South 17.0 8.5 2 2
East 15.0 7.5 2 2
North 10.0 10.0 2 1North has rows of 2 but valid_units of 1, so you can see at a glance that its figures rest on one value. This table can be sorted like any other. If a sort column itself contains NaN, those rows go last unless you set na_position="first", as described in the earlier chapter on sorting.
Sums of nothing: `min_count`
A group whose values are all missing gets a sum of 0.0, not NaN. That can look like real data. The min_count argument sets how many valid values are needed before a result is produced.
print(df.groupby("region")["units"].sum(min_count=2))This prints 15.0 for East, NaN for North and 17.0 for South. North has only one valid value, so it falls below the threshold. The same argument works on Series.sum, prod, and on GroupBy.sum and GroupBy.prod.
To make a whole group NaN as soon as any value is missing, pass a function to agg.
strict = df.groupby("region").agg(
total_strict=("units", lambda s: s.sum(skipna=False)),
)
print(strict)East and South get their totals, and North gets NaN. Python functions are slower than the built-in aggregation names, so use this form only when you need it.
Missing values in the group keys
Missing values can also appear in the column you group by. By default groupby drops those rows. This is the dropna=True default, and it applies without any warning.
keyed = df.copy()
keyed.loc[3, "region"] = None # the East row with 8 units
print(keyed.groupby("region")["units"].sum())
print(keyed.groupby("region", dropna=False)["units"].sum())The first call lists East, North and South, with East at 7.0 because the 8-unit row has lost its region. The row with 8 units appears in no group, so the totals no longer add up to the column total of 42. The second call adds a fourth group labelled NaN with a total of 8.0.
Compare the grand total with the sum of the group totals to catch this problem:
print(keyed["units"].sum()) # 42.0
print(keyed.groupby("region")["units"].sum().sum()) # 34.0If the numbers differ, rows with missing keys were dropped.
Missing values in `value_counts`
value_counts also leaves out NaN by default. Pass dropna=False to see it as its own category.
print(keyed["region"].value_counts())
print(keyed["region"].value_counts(dropna=False))
print(keyed["region"].value_counts(normalize=True, dropna=False))The first call counts five rows. The second counts all six, with one row in the NaN category. With normalize=True, the proportions are computed over the rows that are counted. With the default dropna=True they are fractions of 5, and with dropna=False they are fractions of 6. Decide which denominator you want before you report percentages.
Missing values with `transform`
transform returns a result with one value per original row. The aggregation inside it still skips NaN, but a row's own missing value stays missing in any calculation built on it.
df["region_share"] = (
df["units"] / df.groupby("region")["units"].transform("sum")
)
print(df[["region", "units", "region_share"]])North's total is 10.0. The row with 10 units gets a share of 1.0, and the row with no units gets NaN. The shares in a group add up to 1 over the valid rows only. If a row's group key is missing and dropna=True, transform returns NaN for that row as well.
Missing values in `pivot_table`
pivot_table skips NaN values in the same way, and it drops rows whose index or column key is missing. It also has a fill_value argument for cells with no result.
table = df.pivot_table(
index="region",
columns="product",
values="units",
aggfunc="mean",
fill_value=0,
)
print(table)In this table, North with product B is filled with 0 because its only value was missing. With aggfunc="mean", a 0 there is misleading, because it reads as "no units on average" instead of "unknown". Leave fill_value out when you want NaN to remain visible, and fill only when you know what the gap means.
The following diagram summarises where each default drops data.
Common errors
- Treating a mean as covering all rows. It covers only the valid values, so show
countnext to it. - Comparing
sizewithcountand being surprised. They answer different questions. - Passing
skipnatogroupby(...).sum(). That argument belongs to the Series reductions. Usemin_countor a function inaggfor groups. - Forgetting that all-missing groups sum to
0.0. Usemin_count=1when you wantNaNinstead. - Filling gaps with 0 before computing a mean. Doing so changes the denominator as well as the numerator.
Exercise
Using the sales DataFrame above, change the region of row 2 (North, units missing) to None. Then compute total units per region so that the row with a missing region is kept as its own group. What total does that group show, and what does the same call show without the extra argument?
Show answer
Run d = df.copy(); d.loc[2, "region"] = None; print(d.groupby("region", dropna=False)["units"].sum()). The NaN-key group contains a row whose units value is also missing, so its sum is 0.0. Without dropna=False the group does not appear at all, and the result lists only East (15.0), North (10.0) and South (17.0).
Exercise
The units mean is 8.4 when gaps are skipped. What is it when gaps are filled with 0, and which Series method gives the number of valid values used for the 8.4?
Show answer
Filling with 0 gives 42 / 6 = 7.0, using df["units"].fillna(0).mean(). The number of valid values behind the 8.4 is 5, from df["units"].count().