الانتقال إلى المحتوى
Machine LearningFeature Engineering· 7 دقائق للقراءة

Filling Missing Values with the Mean Isn't Neutral

The mean of the answers isn't the mean of the gaps. Keep the fact that a value was missing, or let the model see it.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • scikit-learn 1.9
محتويات المقال

A retail team predicts yearly spend from a sign-up form where income is optional. They fill the blanks with df.fillna(df.mean()), train a linear regression and get an of 0.488. Predictions for their best customers come out consistently too low. Nobody suspects the one-line imputation, because the mean is the most neutral number there is. Except it isn't neutral: in this data, the customers who skip the income question are mostly the ones who earn the most.

The common misconception

Many developers treat mean imputation as a harmless way to make the data complete. That's understandable:

  • The mean is the best single guess when you know nothing else, and filling with it leaves the column's average unchanged.
  • It's the default. SimpleImputer uses strategy="mean" unless told otherwise, and pandas makes it one line.
  • With a handful of gaps scattered at random, it really does little harm.
  • Dropping incomplete rows feels worse: it throws away whole customers, so filling looks like the conservative choice.

The half-truth: the mean preserves the column's average. It changes almost everything else, and it deletes a piece of information that was in the data all along: which values were missing.

What actually happens

Any filled value is a guess. The question is what the guess hides.

The same guess for every gap

infers missing values from the known part of the data. SimpleImputer is univariate: it looks only at the column being filled, so every missing row gets exactly the same number. Those rows sit at the mean, adding nothing to the column's spread while counting toward its size, so the variance shrinks. They also carry no link to the target or to other columns, which dilutes the relationships the model is supposed to learn. Switching to the median doesn't change this: it's a different number, but still one number for every gap. Google's Machine Learning Crash Course puts it simply: imputed values are rarely as good as the actual values.

The mean of the answers isn't the mean of the gaps

The mean you fill with is computed from the people who answered. If whether someone answers depends on the answer itself, the two groups differ, and the fill value is wrong for exactly the rows it's used on. Statisticians call this "missing not at random". The script simulates it: high earners mostly skip the income question.

Python
import numpy as npimport pandas as pdfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import KFold, cross_val_scorefrom sklearn.pipeline import make_pipelinerng = np.random.default_rng(0)income = rng.normal(50, 15, 2000)  # yearly income, thousandsage = rng.uniform(20, 65, 2000)spend = 2 * income + 0.5 * age + rng.normal(0, 10, 2000)skip = (income > 60) & (rng.random(2000) < 0.8)  # high earners skip itX = pd.DataFrame({"income": np.where(skip, np.nan, income), "age": age})fill, real = X["income"].mean(), income[skip].mean()print(f"imputed {fill:.1f}, skipped rows really average {real:.1f}")model = make_pipeline(SimpleImputer(strategy="mean"), LinearRegression())cv = KFold(n_splits=5, shuffle=True, random_state=0)print(f"R^2 {cross_val_score(model, X, spend, cv=cv).mean():.3f}")# imputed 44.6, skipped rows really average 68.7# R^2 0.488

The imputer fills every gap with 44.6 thousand, while the people behind those gaps actually average 68.7. The model now sees high spenders with average incomes, can't explain them, and its R² drops to 0.488. Nothing in the pipeline raised an error or a warning. The data just quietly says something false.

The gap is a feature

The fix in the second script is one argument. With add_indicator=True, SimpleImputer appends a 0/1 column for every feature that had missing values during training, the output of scikit-learn's MissingIndicator. The linear model learns one more weight, for "income was skipped", which in this data means "probably earns a lot". R² climbs to 0.867.

The Crash Course recommends the same thing: a good dataset tells the model which values are imputed and which are actual, with a Boolean column such as temperature_is_imputed. scikit-learn's own imputation example adds the indicator to every strategy it compares.

Or let the model see the gap

HistGradientBoostingRegressor and HistGradientBoostingClassifier accept NaN directly. At each split, the tree learns whether rows with a missing value should go left or right, based on which gives the better gain, and when missingness is predictive it can split on "missing or not" itself. With no imputer at all, it scores 0.847 here.

StrategyWhat it doesUse it when
Drop incomplete rowsLoses data, and skews the sample if gaps aren't randomGaps are few and you have enough complete rows
Mean or median fillOne value for every gap; the median resists outliersGaps are rare and random; median for long tails
Fill + add_indicator=TrueKeeps the "was missing" signal next to the fillThe default for linear and distance-based models
IterativeImputer, KNNImputerEstimate each gap from the other columnsColumns predict each other; IterativeImputer is still experimental
Native NaN supportLearns where missing rows go at each splitHistGradientBoosting models

How to apply it in your project

  1. Measure the gapsCount missing values per column, and compare the target for rows with and without each value.
  2. Ask why the value is missingAn optional field, a sensor that was down, or an event that never happened? "Never ordered" isn't an average order date; it deserves its own signal.
  3. Keep the signalUse add_indicator=True for linear, distance-based and neural models, or a model with native NaN support such as HistGradientBoosting.
  4. Choose the fill deliberatelyMedian for skewed columns with outliers, a multivariate imputer when other columns can predict the missing one.
  5. Compare inside a pipelineCross-validate dropping, mean fill, fill plus indicator, and native NaN handling, with the imputer inside the pipeline so each fold fits it on training rows only.

Key takeaways

  • Mean imputation gives every gap the same value: the spread shrinks, and the fact that a value was missing is lost.
  • When missingness depends on the value, the mean of the answers is wrong for the gaps: 44.6 against 68.7 here.
  • A missing indicator turns the gap into a feature; in the example, R² rose from 0.488 to 0.867.
  • Fit imputers on training data inside a pipeline, and ship them with the model.

📚 المصادر

  1. Imputation of missing values — scikit-learn User Guide
  2. Imputing missing values before building an estimator — scikit-learn examples
  3. Data characteristics — Google Machine Learning Crash Course
  4. Histogram-Based Gradient Boosting: Missing values support — scikit-learn User Guide
  5. Common pitfalls and recommended practices — scikit-learn User Guide

التعليقات (0)