Sub topic 12
Choosing a Strategy
This chapter assumes you can use isna, dropna, fillna, ffill, interpolate and groupby. It also assumes you know the three missingness mechanisms: MCAR (missing completely at random), MAR (missing at random, explained by other columns) and MNAR (missing not at random, explained by the missing value itself). The goal is to pick one method per column and record why.
Ask three questions per column
There is no best method for the whole DataFrame. Decide column by column.
- Is the column required? If a row is useless without it, such as the target of a model or a join key, drop the row with
dropna(subset=[...]). - Why is it missing? Check whether missingness relates to other columns. For example,
df.groupby("team")["score"].apply(lambda s: s.isna().mean())shows whether one team has far more gaps than the others. - Does the data have order or groups? Ordered data suggests
ffillorinterpolate. Grouped data suggests a group-wise fill. Neither suggests a constant or a statistic.
Match the method to the mechanism
| Situation | Reasonable choice | Risk |
|---|---|---|
| MCAR, few rows affected | `dropna` | Little bias, but you lose data |
| MCAR, many rows affected | Median or constant fill | Shrinks variance |
| MAR, gaps explained by a group | Group-wise fill | Wrong if the groups are too small |
| Time series with short gaps | `interpolate` or `ffill` | Invents values across long gaps |
| MNAR, such as high earners skipping an income question | Fill with a label and add a flag column | Any numeric fill is biased |
MNAR is the hard case. No fill can recover values that are missing because of what they would have been. Keep the missingness visible instead of hiding it.
Record every decision in code
Write the strategy as one function. Add a flag column before you fill, so the information about which values were filled survives. Return counts so you can check the effect.
import numpy as np
import pandas as pd
raw = pd.DataFrame({
"team": ["a", "a", "b", "b", "b"],
"age": [25, np.nan, 31, np.nan, 40],
"score": [10.0, np.nan, 20.0, 22.0, np.nan],
"city": ["Oslo", "Oslo", "Rome", None, "Rome"],
})
def clean(raw):
df = raw.copy()
report = {"rows_in": len(df)}
# score is required, so rows without it are dropped
df = df.dropna(subset=["score"])
report["rows_dropped"] = report["rows_in"] - len(df)
# age: keep a flag, then fill with the median
df["age_was_missing"] = df["age"].isna()
df["age"] = df["age"].fillna(df["age"].median())
report["age_filled"] = int(df["age_was_missing"].sum())
# city: a label keeps the gap visible
df["city"] = df["city"].fillna("unknown")
assert df.isna().sum().sum() == 0
return df, report
clean_df, report = clean(raw)
print(clean_df)
print(report)The function leaves the input untouched, assigns results back instead of using inplace, and fails loudly through the assert if any gap remains. The report shows 2 rows dropped and 1 age filled. If those numbers surprise you, the strategy is wrong for this data.
Document the choice
For each column, write down what you did and why. A comment or a docstring is enough. Include the fraction of values affected and your belief about the mechanism, for example "age: 12% missing, assumed MCAR, median fill, flag column added". Someone rerunning your analysis can then challenge the assumption instead of finding it by accident.
Exercise
A survey has an income column with 30% missing values. You suspect that people with high incomes skipped the question. Which strategy fits, and what should you add to the DataFrame?
Show answer
This is likely MNAR, so a median or mean fill would bias the results toward the middle. Avoid dropping rows silently too. Keep the gaps visible by adding a flag column such as df["income_missing"] = df["income"].isna(). Then either analyse the missing group separately or report results with and without the filled values. State the MNAR assumption in your documentation.
Exercise
In the clean function, why is the age_was_missing flag created before fillna?
Show answer
After fillna, isna() returns all False, so the record of which values were filled would be gone. Creating the flag first preserves that information.