Sub topic 11
Why the Data Is Missing
What this chapter assumes
You should already know how to detect missing values with isna and notna, count them per column, and use groupby. Earlier chapters showed how to drop and fill missing values. This chapter covers the question that comes before that choice: why are these values missing? The answer decides which fix is safe and which one quietly distorts your results.
Why the reason matters
Two columns can each have 20% missing values and need very different treatment. Suppose a survey has a blank income field. Maybe a few forms were lost in the mail. Maybe older respondents skipped the question more often. Maybe people with high incomes refused to answer.
In each case df["income"].isna().sum() returns the same kind of number. But dropping the blanks, or filling them with the mean, gives a trustworthy result in the first case and a biased one in the others.
Statisticians describe this with three mechanisms. They come from the literature on missing data, and pandas has no feature for them. They are a way of reasoning about your data before you pick a method.
The three mechanisms
MCAR: missing completely at random
A value is missing for reasons unrelated to any data, observed or not. Examples are a sensor that randomly drops 2% of readings, or a form lost in transit. The rows with missing values are a random sample of all rows.
Dropping rows is the least harmful under MCAR. You lose rows, so your estimates are less precise, but they are not shifted in a particular direction.
MAR: missing at random
The chance that a value is missing depends on other columns you have, not on the missing value itself. The name is confusing, because the data is not missing "randomly" in the everyday sense. For example, older respondents skip the income question more often. Given age, whether income is missing is unrelated to the income value.
Under MAR, simple dropping or global-mean filling can bias results. Using the columns that explain the missingness can fix this. Group-wise filling with groupby and transform is one such approach.
MNAR: missing not at random
The chance that a value is missing depends on the missing value itself, or on something you did not record. High earners hide their income. Patients who feel worst miss their follow-up visit.
The values you cannot see differ systematically from the ones you can. No pandas operation on the observed data repairs this. You need outside knowledge, a different data source, or an explicit statement of the limitation.
| Mechanism | Missingness depends on | Typical example | Effect of plain dropping |
|---|---|---|---|
| MCAR | Nothing | Randomly lost records | Fewer rows, usually little bias |
| MAR | Other observed columns | Older people skip a question | Can bias results unless you adjust |
| MNAR | The missing value itself or unrecorded factors | High earners hide income | Biased, and the data alone cannot show it |
Simulating the three mechanisms
The clearest way to see the difference is to create each kind of missingness yourself, so you know the true answer. The code below builds a dataset where income rises with age. It then hides income values in three ways and compares the means.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2000
age = rng.integers(18, 80, size=n)
income = 20_000 + 600 * (age - 18) + rng.normal(0, 8_000, size=n)
df = pd.DataFrame({"age": age, "income": income.round()})
# MCAR: every value has the same 20% chance of being hidden
mcar = df["income"].mask(rng.random(n) < 0.20)
# MAR: people aged 50 or older are hidden far more often
p_hide = np.where(df["age"] >= 50, 0.40, 0.05)
mar = df["income"].mask(rng.random(n) < p_hide)
# MNAR: the highest 20% of incomes are hidden
cutoff = df["income"].quantile(0.80)
mnar = df["income"].mask(df["income"] > cutoff)
means = pd.Series({
"true mean": df["income"].mean(),
"MCAR": mcar.mean(),
"MAR": mar.mean(),
"MNAR": mnar.mean(),
}).round(0)
print(means)Series.mask replaces values with NaN where the condition is true. Series.mean skips missing values by default, so each mean uses only the observed incomes.
The MCAR mean lands close to the true mean, because the visible values are a random sample. The MAR mean is too low, because older, higher-earning people are underrepresented. The MNAR mean is much too low, because the top of the distribution was removed. You can only see the bias here because you hold the full data. With real data, the true mean is unknown.
Probing your own data
You cannot measure MNAR directly, but you can look for evidence of MAR. The method is to turn the missing flag into a column and see whether other columns differ between missing and non-missing rows.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2000
age = rng.integers(18, 80, size=n)
income = 20_000 + 600 * (age - 18) + rng.normal(0, 8_000, size=n)
df = pd.DataFrame({"age": age, "income": income.round()})
p_hide = np.where(df["age"] >= 50, 0.40, 0.05)
df["income"] = df["income"].mask(rng.random(n) < p_hide)
# 1. Compare a numeric column across the two groups
df["income_missing"] = df["income"].isna()
print(df.groupby("income_missing")["age"].mean())
# 2. Compare the missing rate across bands of another column
bands = pd.cut(df["age"], bins=[17, 34, 49, 64, 79])
print(df["income_missing"].groupby(bands, observed=True).mean())The first result shows the average age of rows with and without an income. A clear gap means missingness is related to age, which rules out MCAR. The second result shows the share of missing incomes in each age band. Under MCAR these rates should be similar across bands, apart from sampling noise. Here they jump at age 50, which matches how the data was built.
Other checks follow the same pattern:
- Cross-tabulate the missing flag against a categorical column with
pd.crosstab. - Check whether columns are missing together.
df.isna().corr()gives the correlation between missing flags. Columns that go missing together often share one cause, such as a survey section that was skipped. - Look at when values go missing. If gaps cluster in a date range, the cause may be an outage or a change in how the data was collected.
What the mechanism suggests
Under MCAR, dropping with dropna is defensible when you can afford to lose the rows. Filling with a constant or a statistic also gives roughly unbiased means. It still shrinks the variance, because every filled value sits at the same point.
Under MAR, use the columns that explain the gaps. Filling each missing income with the mean of its age band keeps the group structure that a global mean would erase:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2000
age = rng.integers(18, 80, size=n)
income = 20_000 + 600 * (age - 18) + rng.normal(0, 8_000, size=n)
df = pd.DataFrame({"age": age, "income": income.round()})
true_mean = df["income"].mean()
p_hide = np.where(df["age"] >= 50, 0.40, 0.05)
df["income"] = df["income"].mask(rng.random(n) < p_hide)
band = pd.cut(df["age"], bins=[17, 34, 49, 64, 79])
global_fill = df["income"].fillna(df["income"].mean())
band_mean = df.groupby(band, observed=True)["income"].transform("mean")
band_fill = df["income"].fillna(band_mean)
print(round(true_mean))
print(round(global_fill.mean()))
print(round(band_fill.mean()))The band-based fill lands closer to the true mean than the global fill. It works because age explains the missingness, and the fill uses age. If the real cause were a column you did not include, the fill would not help.
Under MNAR, filling and dropping both leave a bias you cannot measure from the data. Reasonable responses are to collect the missing information, to use a domain-specific assumption and state it, or to report results with a clear note on what is missing. Sensitivity analysis is another option. It reruns your analysis under several assumptions about the hidden values and checks whether the conclusion changes.
Keep a record of what was missing
Once you fill a value, the original gap is hidden. Before you fill, save the missing flag, as in the earlier probe:
import numpy as np
import pandas as pd
df = pd.DataFrame({"age": [25, np.nan, 31, np.nan]})
df["age_missing"] = df["age"].isna()
df["age"] = df["age"].fillna(df["age"].median())
print(df)The flag lets you check later whether filled rows behave differently, and a model can use it as a feature. It is also the starting point for the probes above.
Limits of this classification
- The categories are idealized. Real data often mixes mechanisms: some values are lost at random while others are withheld on purpose.
- MAR depends on which columns you have. A gap that looks MNAR may become MAR once you add the column that explains it.
- Small samples make the probes noisy. A difference of a few percentage points between bands may be chance, so check the group sizes with
groupby(...).size()before trusting a rate. - The mechanism describes a column in a context. Different columns in one table can have different causes.
Summary of the workflow
- Count missing values per column and note the share.
- Add missing-flag columns for the important fields.
- Compare other columns across flagged and unflagged rows, and look at missing rates by group and by time.
- Decide which mechanism is plausible and write down why.
- Pick a handling method that fits, which the next chapter takes up, and record the assumption next to the code.
Exercise
In a customer table, phone is missing far more often for customers in one country than in others. Which mechanism does this point to, and what does it mean for the claim "the missing phones are random"?
Show answer
It points to MAR, because the chance of a missing phone depends on another observed column (country). The claim that the data is missing completely at random (MCAR) is not supported. You should account for country when handling the gaps, for example by comparing groups or filling within each country.
Exercise
Write one line of pandas that returns the share of missing income values within each category of a region column, for a DataFrame df.
Show answer
df["income"].isna().groupby(df["region"]).mean() returns the fraction of missing incomes per region. Because isna() gives booleans, mean() averages them as 0 and 1. The same result comes from df.groupby("region")["income"].apply(lambda s: s.isna().mean()).
Exercise
A fitness app has a weight column. Users who gained weight are less likely to log it. Name the mechanism, and say whether comparing logged and unlogged rows on other columns could prove it.
Show answer
This is MNAR, because missingness depends on the unobserved weight value itself. Comparing other columns could not prove it, because the evidence for MNAR lives in the hidden values. At best the comparison might show associations that fit the story. Outside information, such as a follow-up survey, is needed to confirm it.