Sub topic 4
Telling the imputer what counts as missing
This chapter assumes you can run SimpleImputer with fit and transform and read statistics_. It also assumes you know the four strategies from the previous chapters. Here you will learn how the missing_values parameter decides which entries the imputer treats as gaps.
The default: NaN
By default, SimpleImputer treats np.nan as the marker for a missing entry. That matches how pandas and NumPy represent missing floats, so most data needs no extra setup.
The parameter is missing_values, and its default is np.nan. The imputer does two things with this value:
- When it fits, it ignores every entry equal to the marker. The mean, median or most frequent value is computed from the remaining entries.
- When it transforms, it replaces every entry equal to the marker with the learned fill value.
Any entry that does not match the marker is untouched, even if it looks like a gap to you.
Sentinel values
Real datasets often encode missing data as a placeholder, called a sentinel value. Common sentinels are -1, -999, 0 and strings such as "?" or "unknown". The imputer cannot guess these, because -1 is a valid number in many columns. You must name the sentinel.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1, -1],
[-1, 4],
[3, 6]])
imputer = SimpleImputer(missing_values=-1, strategy="constant", fill_value=0)
print(imputer.fit_transform(X))
# [[1 0]
# [0 4]
# [3 6]]The sentinel also affects the statistics. If you use strategy="mean", the imputer leaves the sentinel out of the average:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1], [-1], [3]])
imputer = SimpleImputer(missing_values=-1, strategy="mean")
result = imputer.fit_transform(X)
print(imputer.statistics_) # [2.]
print(result.tolist()) # [[1.0], [2.0], [3.0]]The mean is 2, not 1, because -1 is excluded. If you forgot missing_values=-1, the sentinel would be averaged in as a real value and would distort every fill.
Marker types
The marker can be a number, a string, np.nan, None, or pandas.NA, depending on the column's data type.
| Data | Marker to pass | Notes |
|---|---|---|
| Float columns | `np.nan` (default) | No setting needed. |
| Integer sentinel | `missing_values=-1` | Matches the integer value exactly. |
| String sentinel | `missing_values="?"` | Use an object or string array. Strategy must be `most_frequent` or `constant`. |
| pandas nullable types | `missing_values=pd.NA` | For columns that use `pd.NA`. |
Here is a string sentinel on a categorical column:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["red"], ["?"], ["red"], ["blue"]], dtype=object)
imputer = SimpleImputer(missing_values="?", strategy="most_frequent")
print(imputer.fit_transform(X).tolist())
# [['red'], ['red'], ['red'], ['blue']]Strings cannot be averaged, so mean and median raise an error on non-numeric data. Use most_frequent or constant for text.
One marker per imputer
A SimpleImputer has exactly one missing_values setting. It applies to every column the imputer sees. Two problems follow:
- A dataset might use
-1in one column and-999in another. - A column might contain both
NaNand a sentinel.
When missing_values is not NaN, scikit-learn also rejects real NaN values in the input. So the imputer cannot handle both kinds at once.
The simplest fix is to convert all sentinels to NaN first and then use the default imputer. In pandas, replace does this per column:
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({"age": [25, -1, 40],
"score": [-999, 7.5, 8.0]})
df = df.replace({"age": {-1: np.nan}, "score": {-999: np.nan}})
imputer = SimpleImputer(strategy="mean")
result = imputer.fit_transform(df)
print(imputer.statistics_) # [32.5 7.75]
print(result.tolist())
# [[25.0, 7.75], [32.5, 7.5], [40.0, 8.0]]Inside a ColumnTransformer, you have another option. Give each group of columns its own imputer with its own missing_values. The next chapters show how to build that.
Summary
missing_valuesnames the one marker the imputer treats as missing. Its default isnp.nan.- Entries that match the marker are excluded from the fit statistics and replaced during transform.
- Use
missing_values=-1ormissing_values="?"for sentinels, and convert mixed markers to NaN before imputing.
Exercise
A column holds the values [10, -999, 30, -999, 20], where -999 means "not measured". You run SimpleImputer(strategy="mean") without setting missing_values. Why does this fail to impute anything, and what single change fixes it? What fill value results after the fix?
Show answer
The default marker is np.nan, and the column contains no NaN. The imputer therefore finds nothing to replace, and -999 stays in the data. Pass missing_values=-999. The fit then ignores the -999 entries, so the mean is (10 + 30 + 20) / 3 = 20, and both -999 entries become 20.0.
Exercise
A DataFrame column mixes NaN and the sentinel -1. Why can one SimpleImputer(missing_values=-1) not handle both, and how can you handle them?
Show answer
One imputer has a single marker. With missing_values=-1 it treats only -1 as missing, and scikit-learn rejects real NaN values in the input. Replace -1 with np.nan first, for example df.replace(-1, np.nan), and then use SimpleImputer with the default marker.