Sub topic 12
Choosing a strategy
This chapter assumes you can detect missing values with isna, and that you know dropna, fillna, interpolate, and groupby with transform. It also assumes you know the missing-data markers NaN, None, and pd.NA. Here you learn how to decide among those tools. No single method is correct for every dataset. The right choice depends on why the values are missing, how many there are, and what you will do with the data afterwards.
Start with an audit, not a fix
Count the missing values before you touch any of them. Look at how many are missing per column, whether the gaps cluster in particular rows, and whether they relate to other columns.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"customer_id": [1, 2, 3, 4, 5, 6],
"region": ["north", "north", "south", "south", "south", "north"],
"income": [52000, np.nan, 61000, np.nan, 58000, 49000],
"signup": pd.to_datetime(
["2026-01-03", "2026-01-04", None, "2026-01-09", "2026-01-10", "2026-01-12"]
),
"churned": [0, 1, 0, 1, np.nan, 0],
})
report = pd.DataFrame({
"missing": df.isna().sum(),
"share": df.isna().mean().round(2),
})
print(report)
df["income_missing"] = df["income"].isna()
print(df.groupby("churned", dropna=False)["income_missing"].mean())The first table tells you where the problem is and how big it is. The second compares the share of missing incomes across churn outcomes. If that share differs between groups, the gaps are probably not random. That leads to the next question.
Why the data is missing
Statisticians describe three mechanisms. They decide whether a simple fix is safe.
| Mechanism | Meaning | Example | Effect of simple fixes |
|---|---|---|---|
| MCAR (missing completely at random) | Missingness is unrelated to any value, seen or unseen. | A sensor drops a reading because of a random network glitch. | Dropping rows loses data but does not bias results. |
| MAR (missing at random) | Missingness depends on other columns you have. | Younger customers skip the income question more often. | Filling within groups of the related column works well. Dropping can bias results. |
| MNAR (missing not at random) | Missingness depends on the missing value itself. | High earners refuse to report income. | No simple fix removes the bias. Treat results with caution. |
You cannot prove which mechanism applies from the data alone. MNAR in particular looks like nothing, because the evidence is exactly what is absent. You can find clues, though. Group-wise comparisons like the one above can show MAR. Domain knowledge and the way the data was collected are your best evidence for MNAR. Ask the people who produced the data why a field is empty.
Decision criteria
Work through these questions in order for each column, not for the whole table.
- Is this a placeholder or a real gap? If values such as
-999or"unknown"were loaded as ordinary data, convert them first. Every later step depends on this. - Does the column matter to your goal? A column you will never use does not need handling. Drop it, or leave it alone.
- How much is missing? A few percent is usually safe to handle with any method. When more than about half of a column is missing, filling invents most of the column, so consider dropping the column or modelling the gap explicitly.
- Is the data ordered? Time series and other ordered data support
ffill,bfill, andinterpolate. Unordered rows do not. - Does a group structure explain the gaps? If so, fill within groups rather than with a global statistic.
- Can a missing value be meaningful? Sometimes "missing" is information, for example a customer who never filled in a phone number. Keep an indicator column.
Matching the method to the situation
| Method | Good when | Risk |
|---|---|---|
| `dropna(subset=...)` | The missing column is the target or a required key. The rows are few and plausibly MCAR. | Loses rows. Biases results if the gaps are MAR or MNAR. |
| `dropna(axis="columns", how="all")` | A column has no data at all. | None worth worrying about. |
| `fillna(constant)` | The constant has a real meaning, such as `0` items bought or `"unknown"` for a label. | A made-up value can look like real data. |
| `fillna(median)` | A numeric column is roughly MCAR and has outliers. | Shrinks variance and weakens correlations. |
| `ffill` or `bfill` | A value persists until it changes, such as a price or a status. | Carries stale values across long gaps. |
| `interpolate` | A numeric series changes smoothly and the rows are ordered. | Invents a plausible path where the real one may have jumped. |
| Group-wise `transform` fill | Gaps are MAR with respect to a categorical column. | Small groups give unstable statistics. |
Median is usually safer than mean for skewed numbers such as income. For a category, a constant label like "unknown" is often better than the most frequent value, because it keeps the gap visible.
Keep a record of what you filled
Filling hides the evidence that a value was ever missing. If the fact of missingness could matter later, record it in a separate column before you fill.
clean = df.dropna(subset=["churned"]).copy()
clean["income_was_missing"] = clean["income"].isna()
group_median = clean.groupby("region")["income"].transform("median")
clean["income"] = clean["income"].fillna(group_median)
print(clean[["customer_id", "region", "income", "income_was_missing"]])This example applies three decisions, one per column:
churned: it is the target, so rows without it cannot be used for training. They are dropped.income: gaps appear related to region and churn, so a group median fills them. The indicator column preserves the original pattern.signup: one missing date is left asNaT. Any date I invented would be a guess with no basis.
The .copy() call avoids a warning about modifying a slice, and the result is assigned back to the column instead of using inplace.
Test how much your choice matters
If a downstream result changes a lot between two reasonable strategies, that result is fragile, and you should say so. A quick sensitivity check compares them side by side.
base = df.dropna(subset=["churned"])
strategies = {
"drop rows": base.dropna(subset=["income"])["income"],
"global median": base["income"].fillna(base["income"].median()),
"region median": base["income"].fillna(
base.groupby("region")["income"].transform("median")
),
}
summary = pd.DataFrame({
name: {"mean": s.mean(), "std": s.std(), "rows": len(s)}
for name, s in strategies.items()
})
print(summary.round(1))Look at the std and rows lines in particular. Median fills keep the row count but pull values toward the middle, so the standard deviation falls. Dropping keeps the real spread but loses rows. Neither is wrong, but you should know which trade you made.
Document the strategy
A cleaning step that nobody can reproduce or audit is a liability. Write down, for each column:
- the placeholder values you converted, and where (for example
na_valuesinread_csv); - how many values were missing before you acted;
- the method you used and why;
- any indicator columns you added;
- what you chose not to do.
Keep this in code, not in memory. A small function with a docstring, or a dictionary of rules applied in one place, is enough. Put the cleaning in one function so the same steps run on training data and on new data.
def clean_customers(raw: pd.DataFrame) -> pd.DataFrame:
"""Missing-data rules for the customer table.
- churned: target, rows without it are dropped.
- income: filled with the median of its region, with an indicator column.
- signup: left as NaT, no defensible fill.
"""
out = raw.dropna(subset=["churned"]).copy()
out["income_was_missing"] = out["income"].isna()
out["income"] = out["income"].fillna(
out.groupby("region")["income"].transform("median")
)
return out
print(clean_customers(df.drop(columns="income_missing")).shape)One further caution applies to modelling. Compute fill statistics such as medians from the training data only, then reuse them on test data. Filling with statistics from the full dataset leaks information from the test set into training.
Common mistakes when choosing
- Applying one method to every column. Each column has its own meaning and its own cause of gaps.
- Filling before checking for placeholders. A
-999left in the data distorts any median or mean you compute. - Dropping rows by default.
df.dropna()with no arguments removes a row if any column is missing, which can discard most of a wide table. Usesubsetto name the columns that really matter. - Interpolating unsorted data. Sort by the ordering column first, or the result is meaningless.
- Trusting a fill as real data. Filled values reduce variance and can create false confidence. Report how much of a result rests on filled values.
Exercise
A survey table has an income column with 8% of values missing. People with very high incomes are more likely to leave it blank. You fill the gaps with the column median and report the average income. Which mechanism is this, and what is wrong with the result?
Show answer
This is MNAR, because the chance of being missing depends on the missing value itself. A median fill places everyone in the middle, so the reported average is biased low and the spread is too small. No standard fill fixes this. You should report the limitation, and consider extra information or a model of the missingness if the result matters.
Exercise
A daily sales table is sorted by date. The price column has gaps of one or two days, and prices stay constant until the next change. The units column has scattered gaps that look random. Choose a method for each column and justify it.
Show answer
For price, use ffill, because a price persists until it changes and the gaps are short. Interpolation would invent prices between changes. For units, the gaps look MCAR, so either drop those rows if they are few, or fill with a median and add an indicator column. Linear interpolation would be wrong if units are noisy and not smooth.
Exercise
Why should you compute a fill median from the training data only when preparing data for a model?
Show answer
A median taken from the full dataset includes information from the test rows, which leaks test data into training and makes the evaluation look better than it is. Compute the statistic on the training set and apply that same value to the test set.