Skip to main content
v2026.11,986 entries · CC-BY 4.0

sklearn impute: SimpleImputer, KNNImputer and IterativeImputer

How to impute missing values with sklearn.impute: SimpleImputer, KNNImputer, IterativeImputer, pipelines that avoid leakage, and fixes for common errors.

Written and maintained by CASRAI Editorial Board

Published

On this page

sklearn impute refers to the sklearn.impute module of scikit-learn, which fills in missing values before a model is fitted. It offers three imputers (SimpleImputer, KNNImputer and IterativeImputer) and a MissingIndicator that flags where values were missing, and each one is fitted on training data and then applied to any array with the same columns.

What sklearn impute is used for in research

Most scikit-learn estimators assume that every value in an array is numerical, so a dataset with gaps cannot be passed to them directly. The user guide notes that discarding whole rows or columns with gaps can throw away useful data, which is why filling the gaps is usually preferred (scikit-learn user guide, section 6.4, Imputation of missing values). Survey, clinical and sensor data nearly always contain such gaps, so imputation is a routine preprocessing step in analysis scripts written in Python.

The module groups its tools by how much information they use. SimpleImputer works on one column at a time. KNNImputer and IterativeImputer use the other columns as well. MissingIndicator does not fill anything; it records which entries were missing.

sklearn imputer: the class names

Searches for “sklearn imputer” usually mean SimpleImputer, the class that replaced the old sklearn.preprocessing.Imputer. That older class was removed after scikit-learn 0.20, so tutorials that import it no longer run on current releases. Use from sklearn.impute import SimpleImputer instead.

sklearn imputation: single and multiple

All three imputers return one completed dataset, which is single imputation. The documentation explains that IterativeImputer cannot change the number of samples in transform, so multiple imputation is achieved by running the imputer repeatedly with different random seeds and sample_posterior=True. Pooling the repeated analyses is a separate step that the module does not do for you; see Rubin’s rules for pooling imputed estimates and the mice package in R for that workflow. Whether imputation is appropriate at all depends on why the data are missing, which MCAR, MAR and MNAR diagnosis addresses.

How to install or access scikit-learn

The scikit-learn installation page (version 1.9.1 at the time its page was read) gives two routes. With pip, create and activate a virtual environment, then install:

  1. python -m venv sklearn-env
  2. source sklearn-env/bin/activate (on Windows: sklearn-envScriptsactivate)
  3. pip install -U scikit-learn

With conda, run conda create -n sklearn-env -c conda-forge scikit-learn and then conda activate sklearn-env. To confirm the installation and record the version for your methods section, run python -c "import sklearn; sklearn.show_versions()". The same page lists minimum dependency versions of NumPy 1.24.1 and SciPy 1.10.0 for that release. Cite the version you actually used, so that the analysis can be reproduced.

How to impute missing values step by step

Step 1: Start with SimpleImputer

  1. Import the class and NumPy: import numpy as np and from sklearn.impute import SimpleImputer.
  2. Create the imputer. The documented signature is SimpleImputer(*, missing_values=np.nan, strategy='mean', fill_value=None, copy=True, add_indicator=False, keep_empty_features=False). The strategy can be 'mean', 'median', 'most_frequent' or 'constant'; the last two also work on strings and categorical data.
  3. Call fit on the training data. The imputer learns one statistic per column and stores them in statistics_.
  4. Call transform on any array with the same columns to replace each missing value with that column’s statistic.

The documentation’s own example fits on [[7, 2, 3], [4, np.nan, 6], [10, 5, 9]] with the mean strategy, then transforms [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]]. Column 2 had observed values 2 and 5, so its mean is 3.5, and the output is [[7, 2, 3], [4, 3.5, 6], [10, 3.5, 9]]. Column 1 has a mean of 7 from the values 7, 4 and 10.

When fill_value is left as None it defaults to 0 for numeric data and to "missing_value" for string or object data, but only with strategy='constant'. With most_frequent, ties are broken by returning the smallest value.

Step 2: Move to KNNImputer when columns carry information about each other

KNNImputer replaces a missing value with the average of that feature over the n_neighbors nearest samples that have it. The default distance is nan_euclidean, which tolerates missing entries, and weights can be 'uniform' or 'distance'. If no neighbour has a valid value, the training mean for that feature is used. In the documentation’s example, X = [[1, 2, np.nan], [3, 4, 3], [np.nan, 6, 5], [8, 8, 7]] with n_neighbors=2 becomes [[1, 2, 4], [3, 4, 3], [5.5, 6, 5], [8, 8, 7]]. A fuller treatment of the neighbour method is in the KNN in scikit-learn guide.

Step 3: Use IterativeImputer for model-based filling

IterativeImputer models each feature with missing values as a function of the other features, in a round-robin fashion, controlled by max_iter, random_state, sample_posterior and estimator. Passing a random forest as the estimator gives an approach comparable to missForest, according to the user guide. The class is experimental, so it must be enabled before it can be imported:

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

In the documentation example, fitting on [[1, 2], [3, 6], [4, 8], [np.nan, 3], [7, np.nan]] and transforming [[np.nan, 2], [6, np.nan], [np.nan, 6]] returns values that round to [[1, 2], [6, 12], [3, 6]], because the second column is roughly twice the first in the training rows.

Step 4: Keep the imputer inside a pipeline

Fitting an imputer on the whole dataset before splitting lets information from the test rows shape the training data, a form of training-data leakage. The scikit-learn example on missing values avoids this by placing the imputer and the model in one object with make_pipeline(imputer, regressor) and scoring it with cross_val_score, so the imputer is refitted on the training portion of each fold. A minimal pattern is:

from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestRegressor
model = make_pipeline(SimpleImputer(strategy='median', add_indicator=True), RandomForestRegressor(random_state=0))
scores = cross_val_score(model, X, y, scoring='neg_mean_squared_error', cv=4)

The choice of median here follows the example’s own note that the median is more robust than the mean for long-tailed variables or variables with very large magnitude.

Step 5: Add missingness indicators when the pattern may matter

Setting add_indicator=True on SimpleImputer appends binary columns from a MissingIndicator. Fitting the mean imputer on [[1, 2], [np.nan, 3], [7, 6]] with add_indicator=True gives [[1, 2, 0], [4, 3, 1], [7, 6, 0]]: the middle row’s first value became 4 and its indicator is 1. MissingIndicator can also be used alone with features='missing-only' (the default) or features='all', and its features_ attribute lists the columns that were indexed.

How to read the output

All imputers return a NumPy array by default, so column names are lost. The SimpleImputer page lists feature_names_in_ (added in version 1.0) and support for set_output with pandas, and with polars from version 1.4, so a DataFrame can be returned instead.

  • statistics_ shows the value learned for each column. Reporting these numbers lets a reader reproduce the fill.
  • indicator_ holds the fitted MissingIndicator when add_indicator=True.
  • With indicators on, the extra binary columns come after the original columns, as in the output [[1, 2, 0], [4, 3, 1], [7, 6, 0]] above.
  • inverse_transform works only when add_indicator=True, and only for features that have an indicator.

An imputed value is an estimate, not an observation. The scikit-learn page on imputation warns that SimpleImputer with a powerful learner can match or beat the more elaborate imputers, while with a weak learner imputation often performs poorly, so no imputer is best by default. Report which class and settings you used, the share of values filled per variable and the random seed.

Troubleshooting sklearn impute

ImportError for IterativeImputer

The class is experimental. Add from sklearn.experimental import enable_iterative_imputer before importing it from sklearn.impute.

A column disappeared after transform

The documentation states that columns that are entirely missing at fit time are dropped by transform, unless strategy='constant' or keep_empty_features=True. The latter parameter was added in version 1.2.

A new missing value at transform time has no indicator

Features with no missing values at fit time get no indicator, even if they contain missing values when transformed. Fit on data that represents the missingness you expect.

Imputed results look distorted by scale

The scikit-learn missing-values example notes that KNNImputer is sensitive to feature scale and that IterativeImputer can be hurt by features on very different scales. It rescales with RobustScaler before the imputer on its California housing data. Scaling inside the pipeline keeps this leak-free.

Sparse matrices

The user guide advises against encoding missing values as implicit zeros in sparse data, because the imputer then cannot tell them apart from true zeros.

Version differences

  • sklearn.preprocessing.Imputer was replaced by SimpleImputer in 0.20 and is removed.
  • n_features_in_ arrived in 0.24 and feature_names_in_ in 1.0.
  • keep_empty_features arrived in 1.2, a callable strategy in 1.5 and polars output in 1.4.

Free alternatives to sklearn impute

Which tool to use depends on what the analysis must report. The options below are the ones the sources and the related CASRAI guides cover.

Option What it does Where to read more
Delete incomplete rows or columns Avoids imputing but discards the observed values in those rows or columns, as the scikit-learn user guide notes Listwise vs. pairwise deletion
IterativeImputer with a random forest estimator Model-based filling that the user guide compares to missForest scikit-learn user guide, section 6.4
mice in R Multiple imputation by chained equations in R, with a separate imputation model for each variable; listed on CRAN under GPL-2 or GPL-3 CRAN package page for mice

Sources

Data: scikit-learn sklearn.impute classes compared

Original comparison of the four tools in sklearn.impute (SimpleImputer, KNNImputer, IterativeImputer, MissingIndicator), compiled from the scikit-learn user guide section 6.4 and the SimpleImputer API page: whether each uses other columns, whether it fills values, and the documented key settings.

scikit-learn sklearn.impute classes compared
ClassUses other columnsFills missing valuesKey settings in the documentationDocumented caveat
SimpleImputerNo (per-column statistic)Yesstrategy: mean, median, most_frequent, constant; add_indicator; keep_empty_featuresmost_frequent and constant also work on strings and categorical data; all-missing columns dropped unless strategy is constant or keep_empty_features=True
KNNImputerYes (nearest samples)Yesn_neighbors; weights: uniform or distance; metric nan_euclideanSensitive to feature scale; uses the training mean if no neighbour has a valid value
IterativeImputerYes (round-robin regression)Yesmax_iter; random_state; sample_posterior; estimatorExperimental: needs enable_iterative_imputer; very different scales can hurt it
MissingIndicatorNot applicableNo (flags only)features: missing-only (default) or allUsed alone or via add_indicator; features_ lists indexed columns

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about sklearn impute: SimpleImputer, KNNImputer and IterativeImputer

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →