Data analysis · Intermediate · 16 min
Handle missing data without distorting your results
By Padding · Updated 18 Nov 2026
Python 3.15.2 · pandas 3.1.1 · NumPy 2.5.5 · uv 0.13 (checked on python:3.15-slim)
You will measure where a survey's gaps are, compare dropping rows, mean, median, group-wise and time-series fills by how far each moves the averages, add missing-value flags and write down the choice you made.
On this page
Every real dataset has gaps, and pandas makes them easy to make disappear: dropna() removes them and fillna() papers over them, both in one line, and neither warns you. The trouble is that the reason a value is missing decides whether those lines are harmless or quietly wrong. If ages were lost at random by a broken form, dropping those rows costs you a little precision. If the people who earn the most are the ones who skip the income question, every average you compute from the answers is too low, and filling the gaps with the average keeps it too low.
In this tutorial you generate a small survey where exactly that happens, so you know the true answer and can measure how far each method misses it. You check where the gaps are by column and by group, compare dropping rows with mean, median and group-wise fills, try four ways to fill gaps in a daily time series, add flag columns that record what you filled, and write a short note of the decisions. Clean a CSV file with pandas covers the basic missing-value step; this page is about choosing between the options.
Step 1 · Set up the project and generate the data
Make a throwaway folder, start a uv project and add pandas and NumPy, pinned so your numbers match the ones below:
mkdir -p ~/missing-data-demo
cd ~/missing-data-demo
uv init --no-package --python 3.15
uv add "pandas==3.1.1" "numpy==2.5.5"The generator writes two pairs of files. survey.csv has 800 respondents with region, education, age and monthly income in a made-up currency; the chance of skipping the income question rises with income, and about 4% of ages are lost at random. usage.csv is six weeks of daily mobile data use in megabytes, higher at weekends, with nine days the app failed to log. The _truth files keep the complete values. You will never have those for real data; here they let you score each method.
cd ~/missing-data-demo
cat > generate.py <<'PY'
import numpy as np
import pandas as pd
rng = np.random.default_rng(2026)
# Survey: 800 people, monthly income in a made-up currency.
n = 800
levels = ["secondary", "diploma", "degree", "postgraduate"]
education = rng.choice(levels, size=n, p=[0.35, 0.30, 0.25, 0.10])
base = {"secondary": 180, "diploma": 260, "degree": 400, "postgraduate": 620}
income = np.array([base[e] for e in education]) * rng.lognormal(0, 0.35, size=n)
survey = pd.DataFrame({
"respondent_id": np.arange(1, n + 1),
"region": rng.choice(["North", "South", "East", "West"], size=n),
"education": education,
"age": rng.integers(18, 66, size=n),
"monthly_income": income.round(0),
})
survey[["respondent_id", "monthly_income"]].to_csv("survey_truth.csv", index=False)
# Higher earners are more likely to skip the income question.
rank = survey["monthly_income"].rank(pct=True)
skips = rng.random(n) < 0.05 + 0.45 * rank**2
survey.loc[skips, "monthly_income"] = np.nan
# A few ages are lost at random, unrelated to anything else.
survey["age"] = survey["age"].astype("float64")
survey.loc[rng.random(n) < 0.04, "age"] = np.nan
survey.to_csv("survey.csv", index=False)
# Daily mobile data use (MB) for six weeks, with days the app did not log.
days = pd.date_range("2026-09-01", periods=42, freq="D")
weekend = days.day_of_week >= 5
usage_mb = 300 + 2 * np.arange(42) + np.where(weekend, 180, 0) + rng.normal(0, 25, 42)
usage = pd.DataFrame({"date": days, "usage_mb": usage_mb.round(0)})
usage.to_csv("usage_truth.csv", index=False)
gaps = [8, 9, 15, 25, 26, 36, 37, 38, 39]
usage.loc[gaps, "usage_mb"] = np.nan
usage.to_csv("usage.csv", index=False)
print("survey rows:", len(survey))
print("usage days:", len(usage))
PY
uv run generate.pydefault_rng(2026) fixes the random seed, so the same NumPy version gives the same data on every machine.
Check it worked
The script prints survey rows: 800 and usage days: 42. The folder now holds survey.csv, survey_truth.csv, usage.csv and usage_truth.csv. Open survey.csv in a text editor: some lines end in a comma with nothing after it, which is an empty income.
Step 2 · Measure the gaps by column and by group
Before you choose a fix, find out how much is missing, where, and whether the gaps line up with anything you can see. Counting by column tells you how much; splitting the missing rate by groups tells you whether the gaps are random.
cd ~/missing-data-demo
cat > measure.py <<'PY'
import pandas as pd
survey = pd.read_csv("survey.csv")
print("missing values per column:")
print(survey.isna().sum().to_string())
print()
print("share missing per column:")
print(survey.isna().mean().round(3).to_string())
print()
print("rows with any gap:", survey.isna().any(axis=1).sum())
print()
income_missing = survey["monthly_income"].isna()
for col in ["region", "education"]:
rates = income_missing.groupby(survey[col]).mean().round(3)
print(f"share skipping income, by {col}:")
print(rates.sort_values().to_string())
print()
age_rates = survey["age"].isna().groupby(survey["education"]).mean()
print(f"share missing age, by education: {age_rates.min():.3f} to {age_rates.max():.3f}")
PY
uv run measure.pyRead the output in three parts:
- How much. Income is missing for 154 of 800 people (19.2%), age for 30 (3.8%). Because the gaps fall on different rows, 182 rows have at least one, so
survey.dropna()would throw away 23% of the survey to fix two columns. - Region. The skip rate runs from 16.5% in East to 23% in North. With about 200 people per region, a spread like that can be chance.
- Education. The skip rate climbs from 7.3% for secondary to 51.1% for postgraduate. Education goes with income, so this is the visible trace of the real pattern: higher earners skip more. Age, by contrast, is missing at 1% to 5% in every group with no order to it.
You cannot see the missing incomes themselves, so you will never prove why they are missing. What you can do is test the gaps against every column you do have. If the rate shifts with a column that is related to the missing value, treat the gaps as not random.
Check it worked
The output shows monthly_income 154 and age 30 in the counts, rows with any gap: 182, and the education rates rising in the order secondary, diploma, degree, postgraduate, ending at 0.511. If you sort the education rates and they are not in that order, you have a different NumPy version: run uv add "numpy==2.5.5" again.
Step 3 · Compare dropping rows with mean and median fills
Now see what the three most common fixes do to the summary numbers. Dropping keeps only the 646 answers. Mean and median fills keep all 800 rows by putting one value in every gap.
cd ~/missing-data-demo
cat > compare.py <<'PY'
import pandas as pd
survey = pd.read_csv("survey.csv")
truth = pd.read_csv("survey_truth.csv")
income = survey["monthly_income"]
methods = {
"true values": truth["monthly_income"],
"drop missing rows": income.dropna(),
"fill with mean": income.fillna(income.mean()),
"fill with median": income.fillna(income.median()),
}
rows = []
for name, values in methods.items():
rows.append({"method": name, "n": len(values),
"mean": round(values.mean(), 1),
"median": round(values.median(), 1),
"std": round(values.std(), 1)})
table = pd.DataFrame(rows)
print(table.to_string(index=False))
PY
uv run compare.pyThe true mean is 324.3. Every method misses it, each in its own way:
- Dropping rows gives 289.1, 11% low, because the missing people earn more than the ones who answered. A bigger sample would not fix this; it is bias, not noise.
- Filling with the mean gives exactly the same 289.1. Putting the average into every gap cannot move the average. It also stacks 154 identical values in the middle, so the standard deviation falls from 195.9 to 149.9 and the median jumps from 241.0 to 288.0, right next to the fill value of 289.1, because 154 copies of that value now sit in the middle of the data. Anything built on spread, such as a confidence interval or a correlation, now looks more certain than it is.
- Filling with the median is worse for the mean (279.9): in skewed data like income the median sits below the mean, so it drags the average further down.
So on data like this, "fill with the mean" does not fix the bias; it only hides the gaps. The mean is only a safe fill when values are missing at random and you only need the average.
Check it worked
The table has four rows. drop missing rows and fill with mean share the mean 289.1, the mean fill has the smallest std (149.9), and every mean is below 324.3.
Step 4 · Fill within groups
If a column you can see predicts the missing one, fill from people who are alike on that column. Here that column is education: groupby(...).transform("median") gives every row the median income of its own education group, and fillna uses it only where income is empty.
cd ~/missing-data-demo
cat > groupfill.py <<'PY'
import pandas as pd
survey = pd.read_csv("survey.csv")
truth = pd.read_csv("survey_truth.csv")
income = survey["monthly_income"]
group_median = survey.groupby("education")["monthly_income"].transform("median")
survey["income_group_fill"] = income.fillna(group_median)
print("median income by education (answered only):")
print(survey.groupby("education")["monthly_income"].median().sort_values().to_string())
print()
print("true mean:", round(truth["monthly_income"].mean(), 1))
print("overall median fill mean:", round(income.fillna(income.median()).mean(), 1))
print("group median fill mean:", round(survey["income_group_fill"].mean(), 1))
print("gaps left:", survey["income_group_fill"].isna().sum())
print()
# Only possible because you generated the data: what did the skippers really earn?
survey["true_income"] = truth["monthly_income"]
survey["skipped"] = income.isna().map({True: "skipped", False: "answered"})
print("true mean income by education:")
print(survey.pivot_table(index="education", columns="skipped",
values="true_income", aggfunc="mean").round(1).to_string())
PY
uv run groupfill.pyThe group-wise fill gives 309.7, much closer to 324.3 than the 279.9 from one overall median, because a missing postgraduate income now gets 628.5 instead of 241. Most of the gap between methods came from who skipped, and the group fill accounts for that.
It still falls short, and the last table shows why: inside every education group, the people who skipped earned more than the ones who answered (diploma holders who skipped averaged 342.1, against 258.3 for those who answered). A fill can only use what you observed, so it cannot recover a difference that only shows up in the missing values. Grouping by more columns (education and region, say) helps if they predict income, but small groups give unstable medians; keep each group to a few dozen answers or more.
Keep transform in mind for this pattern: unlike agg, it returns one value per original row in the original order, so it lines up with fillna without a join.
Check it worked
The script prints group medians from 176.0 (secondary) to 628.5 (postgraduate), group median fill mean: 309.7, gaps left: 0, and a final table where the skipped column is higher than answered on every row.
Step 5 · Fill gaps in a time series
Time series have an extra piece of information: order. A missing Tuesday sits between a Monday and a Wednesday, and that can be used. Data-use logs are a good example. On prepaid bundles, common in Nigeria, Kenya and across Africa, a phone that runs out of credit or is switched off to save it can stop logging for days. A missing day is not a day with zero use.
cd ~/missing-data-demo
cat > timeseries.py <<'PY'
import pandas as pd
usage = pd.read_csv("usage.csv", parse_dates=["date"]).set_index("date")
truth = pd.read_csv("usage_truth.csv", parse_dates=["date"]).set_index("date")["usage_mb"]
mb = usage["usage_mb"]
gap = mb.isna()
print("days missing:", gap.sum(), "of", len(mb))
print(", ".join(mb[gap].index.strftime("%a %d %b")))
print(f"true total: {truth.sum():.0f} MB")
print(f"total with gaps dropped: {mb.sum():.0f} MB")
print()
weekday_mean = mb.groupby(mb.index.day_of_week).transform("mean")
fills = {
"fill with 0": mb.fillna(0),
"carry last value forward": mb.ffill(),
"interpolate (time)": mb.interpolate(method="time"),
"same-weekday mean": mb.fillna(weekday_mean),
}
weekend = mb.index.day_of_week >= 5
for name, filled in fills.items():
error = (filled - truth).abs()
print(f"{name:25} total={filled.sum():6.0f} "
f"error on weekdays={error[gap & ~weekend].mean():5.1f} "
f"on weekends={error[gap & weekend].mean():5.1f}")
print()
capped = mb.interpolate(method="time", limit=2, limit_area="inside")
print("left empty with limit=2:", ", ".join(capped[capped.isna()].index.strftime("%a %d %b")))
PY
uv run timeseries.pyThe "error" columns are the average distance, in MB, between each filled day and its true value:
- Ignoring the gaps (or filling with 0, which sums the same) reports 12,797 MB for the six weeks against a true 16,486 MB: 22% of the use vanishes.
sum()skips empty values without saying so. - Carrying the last value forward (
ffill) is close on weekdays but copies a Friday into the weekend, missing it by about 209 MB a day. - Interpolation with
method="time"draws a straight line between the neighbours, weighted by the time between them. It is the right tool for something that changes smoothly, such as a temperature or a meter reading, but here the line runs straight through the weekend peak. - Same-weekday mean fills each gap with the average for that day of the week. It is the group-wise fill from the previous step, with the weekday as the group, and it wins on both kinds of day because it uses the weekly pattern.
The last line shows a guard worth using with any of these: limit=2 fills at most two days in a row, and limit_area="inside" only fills between two real values, never past the ends. A four-day gap keeps its last two days empty, so a long outage stays visible for someone to check instead of becoming a confident straight line.
Check it worked
The script prints days missing: 9 of 42, the nine dates, true total: 16486 MB against total with gaps dropped: 12797 MB, four fill lines where same-weekday mean has the lowest errors (32.7 and 33.3), and left empty with limit=2: Fri 09 Oct, Sat 10 Oct.
Step 6 · Add flag columns before you fill
Once a value is filled, nothing in the data says it was a guess. A flag column fixes that: create it from isna() before filling, and keep it. The flags let you rerun any result on answered rows only, and a model can learn from them, because here skipping the question is itself a signal of high income.
cd ~/missing-data-demo
cat > indicators.py <<'PY'
import pandas as pd
survey = pd.read_csv("survey.csv")
survey["income_was_missing"] = survey["monthly_income"].isna().astype("int8")
survey["age_was_missing"] = survey["age"].isna().astype("int8")
group_median = survey.groupby("education")["monthly_income"].transform("median")
survey["monthly_income"] = survey["monthly_income"].fillna(group_median)
survey["age"] = survey["age"].fillna(survey["age"].median())
print("gaps left:", survey.isna().sum().sum())
print("flagged income values:", survey["income_was_missing"].sum())
print("flagged ages:", survey["age_was_missing"].sum())
print()
print("share with a degree or more, by income flag:")
higher = survey["education"].isin(["degree", "postgraduate"])
print(higher.groupby(survey["income_was_missing"]).mean().round(3).to_string())
survey.to_csv("survey_filled.csv", index=False)
PY
uv run indicators.pyAge gets a plain overall median because its gaps showed no pattern in the measuring step; a small, random gap is the case where a simple fill is fine. Income gets the group-wise fill. Both get flags.
The flags already tell you something: 65.6% of the people who skipped income have a degree or more, against 30.7% of those who answered. If you later train a model on this file, build a scikit-learn pipeline with ColumnTransformer shows how to do the fill inside the pipeline (SimpleImputer(add_indicator=True) adds the same kind of flag), so the medians are learned from training rows only.
Check it worked
The script prints gaps left: 0, flagged income values: 154, flagged ages: 30, and shares of 0.307 and 0.656. The first line of survey_filled.csv ends with income_was_missing,age_was_missing. In a spreadsheet, filter income_was_missing to 1: you see 154 rows, each with an education-group median in monthly_income.
Step 7 · Write down what you did
A filled column looks exactly like a measured one to the next person who opens the file, including you in three months. Keep a short note next to the data that says what was missing, what pattern you found, what you did and what it changed. Build it from the data, so the numbers cannot drift from the file:
cd ~/missing-data-demo
cat > document.py <<'PY'
from datetime import date
import pandas as pd
survey = pd.read_csv("survey.csv")
filled = pd.read_csv("survey_filled.csv")
income = survey["monthly_income"]
skip_rate = income.isna().groupby(survey["education"]).mean()
lines = [
f"# Missing data decisions: survey.csv ({date.today():%Y-%m-%d})",
"",
f"Rows: {len(survey)}. Rows with at least one gap: {survey.isna().any(axis=1).sum()}.",
"",
"## monthly_income",
"",
f"- Missing: {income.isna().sum()} of {len(income)} ({income.isna().mean():.1%}).",
"- Pattern: skipping rises with education, from "
f"{skip_rate.min():.1%} ({skip_rate.idxmin()}) to {skip_rate.max():.1%} ({skip_rate.idxmax()}).",
" Higher earners are less likely to answer, so the gaps are not random.",
"- Method: median of the respondent's education group.",
f"- Effect on the mean: {income.mean():.1f} with gaps dropped, "
f"{filled['monthly_income'].mean():.1f} after filling.",
"- Flag: income_was_missing (1 = filled). Report results with and without filled rows.",
"- Still biased low: within each group, the people who skipped earn more than those who answered.",
"",
"## age",
"",
f"- Missing: {survey['age'].isna().sum()} ({survey['age'].isna().mean():.1%}), no pattern by group.",
"- Method: overall median. Flag: age_was_missing.",
]
with open("MISSING_DATA.md", "w", encoding="utf-8") as notes:
notes.write("\n".join(lines) + "\n")
print("\n".join(lines))
PY
uv run document.pyThe last line under income is the one people leave out: what the fix does not fix. Anyone quoting an average income from this file should know it is still an underestimate. Here you know the true mean is 324.3, so you could even say by how much; with real data you would say which way the error goes and why.
If you hand results to someone else, give them two numbers: one from answered rows only, one with filled rows. If the two tell different stories, the conclusion depends on your fill, and that belongs in the report.
Check it worked
The script prints the note and MISSING_DATA.md holds the same text: Rows with at least one gap: 182, income missing 154 of 800 (19.2%), the skip rate from 7.3% (secondary) to 51.1% (postgraduate), and the mean moving from 289.1 to 309.7. When you have finished, delete the folder with rm -r ~/missing-data-demo.
Next steps
- Describe the filled data, and compare spread before and after filling: describe data with summary statistics.
- Unusual values are the other half of a data check: find outliers in your data and decide what to do with them.
- Do the filling inside a model pipeline so test data never leaks into the medians: build a scikit-learn pipeline with ColumnTransformer.
- Go back over the basic cleaning steps around this one: clean a CSV file with pandas.
Part of these paths
Related tutorials
- How to Clean and Summarise a CSV File with pandasYou will take a messy orders CSV with stray spaces, mixed spellings, money written as text, odd dates, missing values and a duplicate row, and clean it with pandas 3.1 on Python 3.15 into a tidy file plus per-country and per-month summaries.
- Describe data with summary statistics that tell the truthYou will summarise 1,200 generated household incomes with the mean, median, mode, standard deviation, IQR and percentiles, see why the mean misleads on skewed data, compare two districts and write up a figure that carries its spread and count.
- Build a scikit-learn pipeline with ColumnTransformerYou will have one scikit-learn pipeline that imputes, scales and one-hot encodes a mixed customer table, trains a churn model, survives cross-validation and unseen categories, and is saved and reloaded with skops instead of pickle.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials