Missing-Value Analysis
Almost every real dataset has holes: a sensor that was offline, a form field someone skipped, a lab test that was never ordered, a column added to the system last year. Before deciding what to do about them (that is Data Preparation's job: dropping, the eight imputation methods, missing-value indicators), you need to know how much is missing, where, and above all why. The why decides which fixes are safe.
Why values go missing
Statisticians distinguish three mechanisms. The names sound abstract; the examples make them concrete:
| Mechanism | Meaning | Example | Consequence |
|---|---|---|---|
| MCAR, missing completely at random | missingness has nothing to do with any value | a lab sample tube broke in transport | dropping rows loses data but does not bias it |
| MAR, missing at random (given other columns) | missingness depends on other, observed columns | clinic B's form has no "smoker" field | can be handled using the other columns (here: the clinic) |
| MNAR, missing not at random | missingness depends on the missing value itself | people with high incomes skip the income question | the observed values are biased; no fix inside the data alone |
You can never fully prove which mechanism holds, but the data gives strong hints, as the examples below show. And often the fact that a value is missing is itself informative: a missing lab test may mean the doctor saw no reason to order it.
Counting, including disguised missing values
Missing values hide behind placeholders. Normalise them to NaN first, then count per column and per row:
import numpy as np
import pandas as pd
screening = pd.DataFrame({
"patient": ["p01", "p02", "p03", "p04", "p05", "p06", "p07", "p08", "p09", "p10"],
"clinic": ["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"],
"age": [34, 51, -1, 45, 38, 62, 29, 55, 47, 41],
"bmi": [24.1, 31.0, 22.5, None, 27.3, 29.8, None, 33.4, 26.0, None],
"smoker": ["no", "yes", "no", "no", "yes", "", "", "", "", ""],
"glucose": [5.1, 7.9, 4.8, 5.5, 999, 6.2, 5.0, 8.1, 5.7, 6.0],
})
placeholders = {"age": [-1], "smoker": [""], "glucose": [999]}
clean = screening.copy()
for col, values in placeholders.items():
clean[col] = clean[col].replace(values, np.nan)
print("missing before normalising:", screening.isna().sum().to_dict())
print("missing after normalising: ", clean.isna().sum().to_dict())
print()
share = clean.isna().mean().round(2)
print("share missing per column:", share[share > 0].to_dict())
per_row = clean.isna().sum(axis=1)
print("missing values per row:", dict(zip(clean["patient"], per_row)))
print("complete rows:", int((per_row == 0).sum()), "of", len(clean))missing before normalising: {'patient': 0, 'clinic': 0, 'age': 0, 'bmi': 3, 'smoker': 0, 'glucose': 0}
missing after normalising: {'patient': 0, 'clinic': 0, 'age': 1, 'bmi': 3, 'smoker': 5, 'glucose': 1}
share missing per column: {'age': 0.1, 'bmi': 0.3, 'smoker': 0.5, 'glucose': 0.1}
missing values per row: {'p01': 0, 'p02': 0, 'p03': 1, 'p04': 1, 'p05': 1, 'p06': 1, 'p07': 2, 'p08': 1, 'p09': 1, 'p10': 2}
complete rows: 2 of 10
Before normalising, pandas saw only the three empty BMIs. After, the table has 10 missing values (1 age, 3 BMIs, 5 smoker answers, 1 glucose), and only 2 of the 10 patients have a complete row. Dropping every incomplete row would throw away most of the data.
Patterns: which values are missing together
Missing values often come in groups: a whole form section skipped, a whole device offline. Counting the combinations of missing columns shows the patterns, and a picture of the missingness matrix shows them at a glance:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
screening = pd.DataFrame({
"clinic": ["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"],
"age": [34, 51, np.nan, 45, 38, 62, 29, 55, 47, 41],
"bmi": [24.1, 31.0, 22.5, np.nan, 27.3, 29.8, np.nan, 33.4, 26.0, np.nan],
"smoker": ["no", "yes", "no", "no", "yes", None, None, None, None, None],
"glucose": [5.1, 7.9, 4.8, 5.5, np.nan, 6.2, 5.0, 8.1, 5.7, 6.0],
})
miss = screening.drop(columns="clinic").isna()
patterns = miss.apply(lambda r: "+".join(miss.columns[r]) or "(complete)", axis=1)
print(patterns.value_counts())
print()
print("share missing by clinic:")
print(miss.groupby(screening["clinic"]).mean().round(2))
fig, ax = plt.subplots(figsize=(5, 3))
ax.imshow(miss.values, aspect="auto", cmap="Greys", interpolation="nearest")
ax.set_xticks(range(miss.shape[1]), miss.columns)
ax.set_ylabel("row")
ax.set_title("missing values (dark)")
fig.tight_layout()
plt.show()smoker 3
(complete) 2
bmi+smoker 2
age 1
bmi 1
glucose 1
Name: count, dtype: int64
share missing by clinic:
age bmi smoker glucose
clinic
A 0.2 0.2 0.0 0.2
B 0.0 0.4 1.0 0.0
smoker is missing for every patient of clinic B and none of clinic A. That is not random at all: clinic B's form has no smoker question. This is MAR: missingness is explained by an observed column, clinic. A model trained on this data could learn "smoker unknown means clinic B", and if clinic B's patients differ, that becomes a shortcut.
Missingness and the label
If the chance of a value being missing differs between classes, the missingness itself predicts the label. Compare the label rate with and without the value:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2000
risk = rng.random(n)
default = (rng.random(n) < 0.05 + 0.3 * risk).astype(int)
income = np.round(rng.normal(50_000, 12_000, n) - 20_000 * risk, -2)
# Applicants in difficulty skip the income field more often:
skip = rng.random(n) < 0.05 + 0.35 * risk * default
income[skip] = np.nan
df = pd.DataFrame({"income": income, "default": default})
print("income missing:", int(df["income"].isna().sum()), "of", n)
print(df.groupby(df["income"].isna().rename("income_missing"))["default"].agg(["count", "mean"]).round(3))income missing: 198 of 2000
count mean
income_missing
False 1802 0.155
True 198 0.626
Among the 1,802 applicants who gave their income, 15.5% defaulted; among the 198 who left it empty, 62.6% did. Filling these gaps with the average income would erase a strong signal; Data Preparation adds a 0/1 missing indicator column for exactly this situation.
When the missing value itself is the reason (MNAR)
The hardest case: the value is missing because of what it would have been. In this simulation, the higher an income, the less likely it is reported:
import numpy as np
rng = np.random.default_rng(1)
true_income = rng.lognormal(10.8, 0.4, 5000)
p_report = np.clip(1.2 - true_income / 80_000, 0.1, 0.95) # rich people report less often
reported = rng.random(5000) < p_report
print(f"reported: {reported.mean():.0%} of people")
print(f"mean income, everyone: {true_income.mean():7,.0f}")
print(f"mean income, reported only: {true_income[reported].mean():7,.0f}")
print(f"share above 80k, everyone: {(true_income > 80_000).mean():.3f}")
print(f"share above 80k, reported only: {(true_income[reported] > 80_000).mean():.3f}")reported: 55% of people
mean income, everyone: 52,840
mean income, reported only: 43,748
share above 80k, everyone: 0.109
share above 80k, reported only: 0.022
Only 55% report, and they are not a fair sample: their mean income is 43,748 against a true 52,840, and the share above 80k looks like 2.2% when it really is 10.9%. Every method that uses only the observed incomes, dropping rows, filling with the mean, even clever imputation, inherits this bias, because the information about the rich is simply not in the data. Detecting MNAR needs knowledge from outside: a known population average, a follow-up survey of non-respondents, or domain expertise.
Pitfalls
- Counting only
NaN: normalise placeholders ("",-1,999,"N/A","unknown") first. - Dropping incomplete rows by default: it can remove most of the data and bias what is left.
- Ignoring the pattern: missingness tied to a source, a time period or the label is a finding, not noise.
- Filling before splitting: imputation values computed on the whole dataset leak test information into training.
Practice
- A column
last_loginis missing for 12% of users. All of them signed up in the last 7 days and have never logged in again. Which mechanism is it, and what does missing mean here?
Answer
It is not really unknown: "missing" means "no login since sign-up", a meaningful value. Represent it explicitly (a flag never_logged_in, or days since sign-up) rather than imputing a date.
- How would you check whether missing
bmivalues in the screening data depend on age?
Answer
Compare the age distribution of rows with and without BMI, for example clean.groupby(clean["bmi"].isna())["age"].describe(). A clear difference suggests MAR with respect to age.
Test yourself
Clinic B's form has no smoker question, so smoker is missing for all its patients. Which mechanism is this?
- MCAR
- MAR: missingness explained by an observed column
- MNAR
- Not missing at all
High earners skip the income question. Why can no imputation method inside the data fix this?
- Imputation is too slow
- The observed values are biased, and the data contains no information about what the high incomes were
- Income cannot be imputed
- It is MCAR
A glucose column contains the value 999 in some rows. What is the first step?
- Compute the mean
- Check the documentation; if 999 means 'not measured', replace it with NaN
- Delete the column
- Scale it
Default rates are much higher among applicants whose income is missing. What should a later model get?
- Nothing; drop those rows
- A 0/1 indicator for 'income missing', so the signal is not lost
- The mean income in those rows, without an indicator
- A random income