Sub topic 1
Why missing values need handling
Most scikit-learn estimators cannot fit a feature matrix that contains missing entries. This chapter explains what a missing entry is in a feature matrix and what happens when an estimator meets one. It also covers how to find missing entries, and how imputation compares with the other ways of dealing with them. Later chapters cover SimpleImputer itself in detail.
Prerequisites
This chapter assumes you already know:
- Basic Python and NumPy arrays, including
dtypeand boolean masks. - pandas DataFrames, including
isna()anddropna(). - The scikit-learn estimator pattern:
fit,transformandpredict. - The difference between training data and test data.
You don't need to know anything about imputation yet.
What a missing value is
A feature matrix X is a two-dimensional table. Each row is a sample and each column is a feature. A missing value is a cell where the measurement does not exist. A survey respondent skipped the income question. A sensor dropped a reading. A join between two tables found no matching record.
In a NumPy array or a pandas numeric column, the standard marker for a missing value is NaN ("not a number"). It is a special floating-point value, available as np.nan. Three consequences follow from that.
NaNis a float, so an integer array cannot hold it. If you putnp.naninto a list of integers, NumPy upcasts the whole array tofloat64.NaNis never equal to anything, including itself.np.nan == np.nanisFalse. To find missing values you must usenp.isnanorpd.isna, not==.- Any arithmetic that touches
NaNproducesNaN. A mean or sum over a column with oneNaNisNaN.
import numpy as np
ints = np.array([1, 2, 3])
with_gap = np.array([1, 2, np.nan])
print(ints.dtype) # int64
print(with_gap.dtype) # float64
print(np.nan == np.nan) # False
print(with_gap.sum()) # nan
print(np.isnan(with_gap)) # [False False True]pandas also uses None in object columns and pd.NA in its nullable dtypes. pd.isna treats all of these as missing. When a DataFrame goes into an imputer, they are all converted to NaN or handled as missing, as later chapters show.
What happens when an estimator meets NaN
Most scikit-learn estimators validate their input and reject NaN. The check happens at the start of fit or predict, so you see the failure immediately rather than getting silently wrong results.
import numpy as np
from sklearn.linear_model import LogisticRegression
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, 5.0],
[4.0, 1.0]])
y = [0, 1, 1, 0]
try:
LogisticRegression().fit(X, y)
except ValueError as err:
print(str(err).splitlines()[0])
# Input X contains NaN.The wording of the message differs between scikit-learn versions, but the error type is ValueError. The full message in recent versions also lists ways to proceed: use an estimator that accepts NaN, put an imputer in a pipeline, or drop the affected samples.
The reason for the rejection is mathematical. A linear model computes a weighted sum of the features. A distance-based model such as k-nearest neighbors computes the distance between rows. A support vector machine computes kernel values. If one term is NaN, the whole sum or distance is NaN, and the optimization has nothing to work with. The algorithm would need a rule for what the gap means, and scikit-learn does not guess one for you.
Some estimators are an exception. The histogram-based gradient boosting models, HistGradientBoostingClassifier and HistGradientBoostingRegressor, handle NaN natively. During training, they learn for each split which side the missing samples should go to.
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, 5.0],
[4.0, 1.0]])
y = [0, 1, 1, 0]
clf = HistGradientBoostingClassifier(min_samples_leaf=1, max_iter=5)
clf.fit(X, y)
print(clf.predict(X).shape) # (4,)Native support is useful, but it applies to a small set of estimators. If you want to compare several model families on the same data, or if you pick a linear model for interpretability, you need to deal with the gaps yourself.
Finding missing values before you fix them
Always measure how much is missing, and where, before choosing a treatment. A column with 2% missing and a column with 60% missing call for different decisions.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [25, np.nan, 40, 31, np.nan],
"income": [40000, 52000, np.nan, 61000, 48000],
"city": ["Oslo", "Rome", None, "Oslo", "Rome"],
})
print(df.isna().sum())
# age 2
# income 1
# city 1
# dtype: int64
print(df.isna().mean())
# age 0.4
# income 0.2
# city 0.2
# dtype: float64
print(len(df.dropna()), "of", len(df), "rows are complete")
# 2 of 5 rows are completeisna().sum() gives the count per column. isna().mean() gives the fraction, because the mean of a boolean column is the share of True values. The last line shows how quickly complete rows disappear. Each column is missing at most 40% of its values, but only 2 of 5 rows have no gap anywhere. The missing entries are spread over different rows, so the complete-row fraction is much lower than any single column's.
Disguised missing values
isna() only finds entries that are actually encoded as NaN, None or pd.NA. Real data often marks missing entries in other ways. Common examples are -1, -999, 0, 9999, an empty string, or text such as "N/A" and "unknown".
These values are dangerous because they pass every validity check and still distort the model.
import pandas as pd
ages = pd.Series([25, -1, 40, 31, -1])
print(ages.isna().sum()) # 0
print(ages.mean()) # 18.8Pandas reports no missing values, and the mean age is 18.8. The mean of the three real ages is 32. The -1 entries are treated as ages and pull the average down. A model would treat "-1 years old" as a real, very young person.
Check each column's value range and its most common values. Convert sentinels to NaN at the start of your pipeline, or tell the imputer which value to treat as missing. The chapter on the missing_values parameter covers the second option.
Why data goes missing
How the data became missing affects which treatment is safe. Statisticians distinguish three cases.
| Mechanism | Meaning | Example | Effect of simple fixes |
|---|---|---|---|
| MCAR (missing completely at random) | The chance of being missing is unrelated to any value, observed or not. | A lab sample is dropped at random. | Dropping rows loses data but adds no bias. Imputation is generally safe. |
| MAR (missing at random) | The chance of being missing depends on other observed columns, not on the missing value itself. | Younger respondents skip the income question more often, and age is recorded. | Row dropping biases the sample. Imputation that uses other columns can help. |
| MNAR (missing not at random) | The chance of being missing depends on the missing value itself. | High earners refuse to report income. | No simple fix removes the bias. The fact that a value is missing carries information. |
You cannot prove from the data alone which mechanism applies, because the evidence for MNAR is by definition the values you do not have. In practice you combine domain knowledge with checks, such as comparing the rows with and without gaps. The MNAR case is why a later chapter introduces indicator columns, which keep the fact "this value was missing" available to the model.
Your options
There are four common ways to handle missing values for a scikit-learn model.
| Option | What it does | Cost |
|---|---|---|
| Drop rows | Remove every sample that has a gap. | Loses training data, and can bias the sample unless the data is MCAR. At prediction time you cannot drop a row, because you still need an answer for it. |
| Drop columns | Remove features with too many gaps. | Loses whatever signal the feature carried. Reasonable for a column that is mostly empty. |
| Impute | Fill each gap with a substitute value. | The substitute is an estimate. It can shrink the column's variance and weaken relationships between columns. |
| Use a model with native support | Let the estimator handle `NaN` itself. | Limits your choice of model. |
The prediction-time point deserves attention. A model deployed in production will receive incomplete rows. A pipeline built on dropping rows has no answer for them, while an imputer can fill the gaps with values learned during training. This is a main reason why imputation is a standard part of preprocessing.
Imputation is not free. If you replace every gap in a column with its mean, the column gets a spike at that mean and its spread shrinks. Correlations with other columns weaken. When only a few percent of values are missing the effect is small. When half the column is missing the effect is large, and you should question whether the column is useful at all. The final chapter in this tutorial discusses these limits and the model-based alternatives.
Where SimpleImputer fits
SimpleImputer is a scikit-learn transformer in sklearn.impute. It follows the same pattern as StandardScaler: you call fit to learn something from the training data, then transform to apply it. For imputation, the thing it learns is a fill value for each column, such as the column mean. It then replaces each missing entry with that column's value.
Because it is a transformer, you can put it before the estimator in a Pipeline. The pipeline runs the imputer first, so the estimator only ever sees complete data.
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, 5.0],
[4.0, 1.0]])
y = [0, 1, 1, 0]
model = make_pipeline(SimpleImputer(strategy="mean"), LogisticRegression())
model.fit(X, y)
print(model.predict(X).shape) # (4,)The same data that raised a ValueError earlier now fits without error. The next chapter explains each part of this code. The overall flow for handling missing data looks like this:
The last box, fitting on training data only, matters enough to get its own chapter. The short version is that the fill values must be computed from the training set and then reused on test data. Computing them on the full dataset leaks information from the test set into preprocessing.
Common errors at this stage
- Treating
isna().sum() == 0as proof the data is clean. Sentinel values and placeholder strings pass this check. Look at value counts and ranges as well. - Dropping rows first and asking questions later.
dropna()is quick, but it can discard most of a dataset when gaps are spread across many columns, as the five-row example showed. - Using
==to findNaN.df["age"] == np.nanisFalsefor every row. Useisna(). - Assuming a message about
NaNmeans onlyNaN. The same validation also rejects infinite values. If you see an error that mentions both, check forinfas well, which often comes from a division by zero upstream. - Imputing a column that should have been dropped or investigated. A column that is 90% missing gives the imputer almost nothing to learn from. Every row ends up with nearly the same value.
Summary
Missing entries are normally stored as NaN, a float, and any arithmetic involving NaN produces NaN. Most scikit-learn estimators therefore raise a ValueError on them, with HistGradientBoostingClassifier and HistGradientBoostingRegressor as the notable exceptions. Before you choose a fix, measure the gaps with isna(), look for disguised values, and think about why the data is missing. Dropping rows is simple but loses data and cannot be applied to new rows at prediction time. Imputation fills the gaps with learned substitute values, and SimpleImputer does this as a regular fit/transform step that slots into a pipeline.
Exercise
A DataFrame has 1,000 rows and 4 columns. Each column is missing about 10% of its values, and the gaps fall on different rows. Roughly what fraction of rows would remain after dropna(), if the gaps were independent across columns? Why does this matter for the choice between dropping and imputing?
Show answer
Each row is complete in a column with probability 0.9, so it is complete in all four with probability 0.9 to the power of 4, which is about 0.66. Roughly 660 rows would remain and about a third of the data would be lost, even though each column is only 10% empty. Dropping rows loses much more data than the per-column figures suggest, so imputation is usually preferable once gaps are spread across several columns.
Exercise
A column called bmi contains the values [22.5, 0, 31.0, 0, 27.8]. df["bmi"].isna().sum() returns 0. Is the column free of missing values? What would you do before imputing, and what would happen to the column mean if you skipped that step?
Show answer
Not necessarily. A body mass index of 0 is physically impossible, so the zeros are probably placeholders for missing measurements. Confirm that with the data owner, then replace the zeros with np.nan (for example with df["bmi"].replace(0, np.nan)). If you skip this step, the mean is (22.5 + 0 + 31.0 + 0 + 27.8) / 5 = 16.26, while the mean of the three real values is about 27.1. Any imputer that used the mean would then fill gaps with a value too low to be realistic.
Exercise
Why can a pipeline that drops incomplete rows fail in production even if it trains well, and how does an imputer address this?
Show answer
At prediction time every incoming row needs a prediction, and some of those rows will have gaps. Dropping the row means no answer is returned for it. An imputer learns fill values from the training data during fit and applies them in transform to any new row, so the model always receives a complete row.