Module 3 · Beginner · Data preparation and EDA

Missing value imputation explained

Missing value imputation for machine learning in Python: mean, median, KNN and iterative imputers, missing indicators, and when blanks carry meaning.

By theprogrammers team · · 15 min read

A bank's loan form has a box for annual income, and a third of applicants leave it blank. Some forgot. Some are self-employed and weren't sure what to write. Some earn a lot and would rather not say. A person reading the forms can shrug and move on, but a model can't: it does arithmetic on every column, and you can't multiply a blank by a weight.

So before a model sees the data, every blank has to be either removed or filled with a sensible guess. Filling in guesses is called missing value imputation, and the right guess depends on why the value is missing. Below, you'll see a model refuse missing values, compare the standard ways of filling them on data where the true answers are known, and find out why a value that's missing for a reason is itself useful information.

What you need first: the scikit-learn tutorial (fit and transform) and train, validation and test sets. For finding and counting missing values in pandas, see handle missing values in pandas in the EDA course.

Key terms

  • Missing value: an empty cell, stored by pandas and NumPy as NaN ("not a number").
  • Imputation: replacing missing values with estimates, so every row can be used.
  • Missing by chance: the blanks are spread randomly, unrelated to anything, like a form lost in the post.
  • Missing for a reason: whether a value is missing depends on the value itself or on other facts, like high earners skipping the income box.
  • Missing indicator: an extra yes/no column that records which values were filled in, so the model can tell real values from guesses.

See it fail: a model meets a blank

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

homes = pd.DataFrame({"rooms": [3, 4, np.nan, 5], "age": [20, np.nan, 35, 10]})
price = [150, 190, 160, 240]
try:
    LinearRegression().fit(homes, price)
except ValueError as error:
    print("ValueError:", str(error).splitlines()[0])
ValueError: Input X contains NaN.

np.nan is how a missing number is written in Python. try/except catches the error so its message can be printed instead of stopping the program.

scikit-learn refuses outright: "Input X contains NaN." Most models work this way. A few, such as histogram-based gradient boosting, accept blanks, but you'll meet them much later.

The simplest fix is to delete every row with a blank. Here that leaves 2 of 4 homes. On real data it often throws away far more than you'd expect, because a row is lost if any of its columns is blank, and it leaves you stuck when a new row with a blank arrives and needs a prediction.

Simple imputation: fill with one number per column

SimpleImputer learns one fill value per column from the training data, then uses it everywhere:

from sklearn.impute import SimpleImputer

imputer = SimpleImputer(strategy="median")
filled = imputer.fit_transform(homes)
print("learned fill values:", imputer.statistics_)
print(filled)
learned fill values: [ 4. 20.]
[[ 3. 20.]
 [ 4. 20.]
 [ 4. 35.]
 [ 5. 10.]]

fit works out each column's median, ignoring the blanks; transform puts those medians into the blanks. statistics_ holds what was learned, and the trailing underscore marks it as something learned in fit. The other strategies are "mean", "most_frequent" (which also works for text columns) and "constant".

Predict first: an income column has a few very rich districts. Will the mean or the median be the safer fill value?

The median, usually. A handful of very rich districts drag the mean upwards, so a mean-filled blank looks richer than a typical district. The median is the middle value, so a few extreme values barely move it. Here, the median of rooms (3, 4, 5) is 4 and the median of ages (20, 35, 10) is 20.

Missing value imputation with a known answer

Real missing values hide their true answers, so you can never check a guess. To compare methods fairly, start with complete data, hide some values on purpose, fill them in, and measure how far off the guesses are. The California housing data has no missing values, so it's ideal: hide 30% of the districts' median incomes, at random.

Download the data: california-housing.csv (1.9 MB), or from the original source, the StatLib repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("california-housing.csv").

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

housing = fetch_california_housing(as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(housing.data, housing.target, test_size=0.25, random_state=0)
rng = np.random.default_rng(0)

def hide_income(data, by_chance=True):
    data = data.copy()
    if by_chance:
        hidden = rng.random(len(data)) < 0.3
    else:
        hidden = (data["MedInc"] > data["MedInc"].quantile(0.6)) & (rng.random(len(data)) < 0.75)
    data.loc[hidden, "MedInc"] = np.nan
    return data, np.asarray(hidden)

train_gaps, train_hidden = hide_income(X_train)
test_gaps, test_hidden = hide_income(X_test)
print(f"share of incomes hidden: {train_hidden.mean():.3f}")
print(f"training rows left if rows with a blank are dropped: {train_gaps.dropna().shape[0]} of {len(train_gaps)}")
share of incomes hidden: 0.294
training rows left if rows with a blank are dropped: 10925 of 15480

hide_income blanks out incomes and returns the gappy copy plus a True/False array saying which ones were hidden, so the guesses can be checked later. by_chance=False is used further down.

About 29% of incomes are now blank. Dropping every row with a blank would keep only 10,925 of 15,480 training districts, throwing away 29% of the data, including all the other seven columns of those rows, which were perfectly good.

Now compare four imputers. Two new ones: KNN imputation fills a blank with the average of the 10 most similar districts, the same idea as k-nearest neighbours; iterative imputation predicts each column with a small regression on the other columns, going round the columns a few times.

from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import KNNImputer, IterativeImputer

def make_imputers():
    return {"mean": SimpleImputer(strategy="mean"), "median": SimpleImputer(strategy="median"),
            "KNN": KNNImputer(n_neighbors=10), "iterative": IterativeImputer(random_state=0)}

true_income = X_test["MedInc"].to_numpy()
for name, imputer in make_imputers().items():
    guesses = imputer.fit(train_gaps).transform(test_gaps)[:, 0]
    error = np.abs(guesses[test_hidden] - true_income[test_hidden]).mean()
    print(f"{name:9} average error of the filled-in incomes: {error:.3f}")
mean      average error of the filled-in incomes: 1.411
median    average error of the filled-in incomes: 1.369
KNN       average error of the filled-in incomes: 1.373
iterative average error of the filled-in incomes: 0.795

IterativeImputer is still marked experimental in scikit-learn, so the first import line switches it on. Each imputer is fitted on the training data and used to fill the test data; [:, 0] takes the first column, MedInc, and [test_hidden] keeps only the values that were hidden.

Mean, median and KNN imputation are all about equally bad: their guesses are off by about 1.4 on average ($14,000 of income). Iterative imputation is much better, at 0.795, because income is predictable from the other columns: rooms per household and location say a lot about how well-off a district is. KNN should have used that too, but it didn\'t. Why not? See the experiment.

Experiment: KNN imputation measures similarity with distances, and in this data Population runs into the thousands while incomes are around 4. Scale the features first, then impute, and see whether KNN catches up.

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler().fit(train_gaps)
knn = KNNImputer(n_neighbors=10).fit(scaler.transform(train_gaps))
scaled_guesses = scaler.inverse_transform(knn.transform(scaler.transform(test_gaps)))[:, 0]
print(f"scaled KNN average error: {np.abs(scaled_guesses[test_hidden] - true_income[test_hidden]).mean():.3f}")
scaled KNN average error: 0.696

StandardScaler ignores blanks when it learns each column's mean and spread, and keeps them as blanks. inverse_transform converts the filled-in values back to the original units so the error is comparable.

With scaled features, KNN imputation\'s error falls from 1.373 to 0.696, now the best of all. Unscaled, "similar districts" meant districts with a similar population, because population\'s numbers are thousands of times bigger than everything else\'s, and population says almost nothing about income. The same lesson as in feature scaling: anything based on distances needs scaled features.

What does a filled-in column look like? Plot the incomes after mean imputation:

import matplotlib.pyplot as plt

mean_filled = SimpleImputer(strategy="mean").fit(train_gaps).transform(train_gaps)[:, 0]
iter_filled = IterativeImputer(random_state=0).fit_transform(train_gaps)[:, 0]
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5), sharex=True, sharey=True)
for ax, values, title in zip(axes, [X_train["MedInc"], mean_filled, iter_filled],
                             ["True incomes", "Mean imputation", "Iterative imputation"]):
    ax.hist(values, bins=60, range=(0, 10))
    ax.set_title(title)
    ax.set_xlabel("Median income ($10,000s)")
axes[0].set_ylabel("Districts")
plt.show()
Three histograms of district median incomes on the same axes. True incomes: a smooth hump peaking around 3 with a long right tail. Mean imputation: the same hump, lower, with one tall spike of almost 5,000 districts at about 3.9, the mean. Iterative imputation: a smooth hump very close to the true one, with no spike.

sharex and sharey give the three charts the same axes, so their shapes can be compared directly.

Mean imputation puts almost 5,000 districts at exactly the same income, about 3.9, a tall spike that doesn\'t exist in real life. The column now looks less spread out than it really is, and every filled district looks perfectly average. Iterative imputation\'s guesses blend into the real shape, because each one is based on that district\'s other features.

When values are missing for a reason

So far the blanks were random. Now hide incomes the way people actually do: three-quarters of the richest 40% of districts leave the box empty. Predict first: what will mean imputation put in for a rich district, and will a model notice?

train_gaps, train_hidden = hide_income(X_train, by_chance=False)
test_gaps, test_hidden = hide_income(X_test, by_chance=False)
print(f"average true income of the hidden districts: {X_train['MedInc'][train_hidden].mean():.2f}")
print(f"average income of the districts left:        {X_train['MedInc'][~train_hidden].mean():.2f}")

complete = make_pipeline(StandardScaler(), LinearRegression()).fit(X_train, y_train)
print(f"\nmodel with no missing values: MAE {np.abs(complete.predict(X_test) - y_test).mean():.3f}")
for name, imputer in [("median", SimpleImputer(strategy="median")),
                      ("median + indicator", SimpleImputer(strategy="median", add_indicator=True)),
                      ("iterative", IterativeImputer(random_state=0)),
                      ("iterative + indicator", IterativeImputer(random_state=0, add_indicator=True))]:
    model = make_pipeline(imputer, StandardScaler(), LinearRegression()).fit(train_gaps, y_train)
    print(f"model with {name:22} MAE {np.abs(model.predict(test_gaps) - y_test).mean():.3f}")
average true income of the hidden districts: 5.61
average income of the districts left:        3.13

model with no missing values: MAE 0.537
model with median                 MAE 0.666
model with median + indicator     MAE 0.620
model with iterative              MAE 0.617
model with iterative + indicator  MAE 0.602

Each model is a pipeline: impute, scale, then fit a linear regression, the straight-line model of the next module. MAE is the average error in $100,000s; lower is better. add_indicator=True adds a yes/no column for "this income was missing".

The hidden districts are rich: their true average income is 5.61, against 3.13 for the rest. Median imputation fills them all with an ordinary income, and the model\'s error rises from 0.537 (no missing values) to 0.666. The missing indicator wins much of that back (0.620), because "income is blank" turns out to mean "probably rich", and the model learns that from the yes/no column. Iterative imputation guesses better from the other columns (0.617), and combining it with the indicator is best of all (0.602). None of them gets back to 0.537: information that was never recorded can\'t be fully recovered.

A real example: Titanic ages

In real data you can't see the hidden values, but you can check whether missingness is linked to the target. The Titanic passenger list is missing 177 of 891 ages.

Download the data: titanic.csv (56 KB), or from the original source, the seaborn-data repository on GitHub. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("titanic.csv").

import seaborn as sns

titanic = sns.load_dataset("titanic")
print(titanic.isna().sum()[lambda counts: counts > 0])
age_missing = titanic["age"].isna()
print(titanic.groupby(age_missing)[["survived", "pclass"]].mean().round(2)
      .rename(index={False: "age known", True: "age missing"}))
age            177
embarked         2
deck           688
embark_town      2
dtype: int64
             survived  pclass
age                          
age known        0.41    2.24
age missing      0.29    2.60

isna().sum() counts the blanks in each column, and [lambda counts: counts > 0] keeps only the columns that have some. Grouping by age_missing compares passengers with and without a recorded age.

Ages are missing for 177 passengers, and deck for 688, more than three-quarters, which makes it a candidate for dropping. The comparison is the interesting part: 41% of passengers with a known age survived, but only 29% of those without one, and they were more often in third class (average class 2.60 against 2.24). Ages were mostly recorded for passengers whose details were better known, the better-off ones. The blank says something about the passenger, so a missing indicator for age is worth trying.

Fit the imputer on training data only

An imputer learns from data, so it follows the same rule as a scaler: fit on the training rows, then transform the training, validation and test rows with what it learned. If you fit it on all the data, the test rows' values leak into the fill values. The data leakage lesson, later in this module, shows how much that can flatter a score, and scikit-learn pipelines make the rule automatic.

Which imputation method to use

SituationMethodWhy
A few blanks, missing by chanceSimpleImputer, median for numbers, most frequent for categoriesFast, hard to get wrong
Many blanks in a column that other columns can predictIterativeImputerUses relationships between columns
Similar rows tend to have similar valuesKNNImputer, after scalingBorrows values from look-alike rows
Missingness could be linked to the value or the targetAny imputer plus add_indicator=TrueThe model can learn from "was missing"
Tree models such as gradient boostingOften no imputation at allHistGradientBoosting models handle NaN themselves
A column that is mostly blankConsider dropping the column, or just the indicatorFew real values to learn from

Practice

  1. Without running code: a column of ages is 25, 30, 35, 40 and one blank. What do mean and median imputation each put in the blank?
Show the answer

The mean of 25, 30, 35 and 40 is 32.5, and the median is also 32.5, because with an even count the median is the average of the middle two (30 and 35). They only differ when the values are skewed.

  1. Fill the homes table using the mean instead of the median. Which value changes?
Show the answer
mean_imputer = SimpleImputer(strategy="mean")
print(mean_imputer.fit_transform(homes))
print(mean_imputer.statistics_.round(2))
[[ 3.         20.        ]
 [ 4.         21.66666667]
 [ 4.         35.        ]
 [ 5.         10.        ]]
[ 4.   21.67]

Only the age blank changes: the mean of 20, 35 and 10 is 21.67, while the median was 20. The rooms blank stays at 4, because the mean and the median of 3, 4 and 5 are both 4.

  1. Fill the Titanic embarked column (the port each passenger boarded at) with its most common value. Which port is it?
Show the answer
port_imputer = SimpleImputer(strategy="most_frequent")
filled_ports = port_imputer.fit_transform(titanic[["embarked"]])
print(port_imputer.statistics_, pd.Series(filled_ports[:, 0]).isna().sum())
['S'] 0

Southampton (S), where most passengers boarded. After filling, no blanks are left (0). For a column with only 2 blanks, the most frequent value is a perfectly sensible choice.

  1. A colleague fills blanks using the mean of the whole dataset before splitting into training and test sets. What's wrong, and how would you fix it?
Show the answer

The fill value has been computed partly from the test rows, so information from the test set has leaked into training, and the test score is slightly optimistic. Split first, fit the imputer on the training rows only, and use it to transform the test rows, or put the imputer in a pipeline.

  1. Why can a missing indicator help even when the imputer's guesses are poor?
Show the answer

When values are missing for a reason, the fact that a value is missing carries information. With the indicator, the model can learn "rows with a blank income tend to be expensive" directly, and correct for the imputer's bad guess.

Interview questions

What are the common ways to handle missing data?

Drop rows or columns, fill with a simple statistic (mean, median or most frequent), use model-based imputation such as KNN or iterative imputation, add missing indicators, or use models that accept missing values natively, such as histogram-based gradient boosting.

Why is dropping rows with missing values often a bad idea?

It throws away all the other information in those rows, often a large share of the data, and it can bias the training data if the missing rows differ from the rest. It also gives no answer when a new row with a blank needs a prediction.

How do you avoid data leakage when imputing?

Fit the imputer on the training data only and apply it to validation and test data, ideally inside a pipeline, so cross-validation refits it on each training fold.

Key takeaways

  • Most models can't handle blanks, and dropping rows wastes data and can't handle new rows with blanks.
  • Simple imputation fills each column with one learned value; the median is safer than the mean for skewed columns.
  • Iterative imputation uses the other columns and gave far better guesses here; KNN imputation needs scaled features.
  • When values are missing for a reason, every imputer guesses badly, and a missing indicator lets the model use the missingness itself.
  • Fit imputers on training data only, ideally inside a pipeline.

Frequently asked questions

Should I impute the target column?

No. Rows with a missing target can't be used for training, because there's no answer to learn from. Drop them from training, and use them only if you need predictions for them.

How many missing values is too many?

There's no fixed limit. A column that is 90% blank has little real information, but its missing indicator might still be useful. Compare validation scores with the column, without it, and with only its indicator.

Is imputation the same as making up data?

In a sense, yes: imputed values are guesses, not measurements. That's why you never report imputed values as facts, and why checking guesses on data with known answers, as here, is a good way to choose a method.

What to learn next

  1. Turn text categories into numbers in one-hot vs label encoding explained, the next lesson.
  2. Find and count missing values in pandas in handle missing values in pandas.
  3. Put the imputer inside a pipeline in scikit-learn pipelines and ColumnTransformer.