Sub topic 4
Telling the imputer what counts as missing
This chapter assumes you can fit and call transform on a SimpleImputer, that you know what statistics_ holds, and that you have used pandas DataFrames. You will learn how the imputer decides which entries to fill, how to point it at a sentinel value such as -1 or "?", and what goes wrong when it looks for the wrong marker.
The default: NaN means missing
SimpleImputer only fills entries that it recognizes as missing. By default, that means np.nan. The constructor signature starts with missing_values=np.nan, so these two lines are equivalent:
from sklearn.impute import SimpleImputer
import numpy as np
a = SimpleImputer(strategy="mean")
b = SimpleImputer(missing_values=np.nan, strategy="mean")The imputer uses this setting in two places:
- During
fit, it ignores every entry that matchesmissing_valueswhen it computes each column's statistic. - During
transform, it replaces every entry that matchesmissing_valueswith that statistic or withfill_value.
An entry the imputer does not recognize as missing is treated as an ordinary value. It can change the learned mean, and it is never replaced. Every other topic in this chapter follows from that rule.
Why datasets need this parameter
Real data rarely arrives with clean NaN markers. Data producers use whatever convention was convenient:
- Numeric codes such as
-1,-999, or9999for "not recorded". 0where the field was left blank, for example in an income column.- Strings such as
"?","unknown","N/A", or an empty string"". Nonein a Python list or object column.pd.NAin pandas columns that use nullable dtypes.
Scikit-learn does not guess which of these is a missing marker, because a guess would be wrong often enough to be harmful. A -1 can be a sentinel in an "age" column and a legitimate reading in a "temperature in Celsius" column. You declare the marker, and the imputer follows your declaration.
What `missing_values` accepts
| Value you pass | Typical use | Notes |
|---|---|---|
| `np.nan` (default) | Float arrays, DataFrames with NaN | Also matches `None` and `pd.NA` once pandas converts them to NaN in a float array |
| An integer, such as `-1` | Integer or float arrays with a numeric code | Matches `-1.0` in a float array too |
| A float, such as `-999.0` | Float arrays with a numeric code | Compared by equality |
| A string, such as `"?"` | Object arrays with text markers | Use `most_frequent` or `constant`, because mean and median need numbers |
| `None` | Object arrays where missing is `None` | Applies to object-dtype data |
| `pd.NA` | pandas nullable dtypes | Needs a reasonably recent scikit-learn version |
You can pass exactly one marker per imputer. There is no list of markers. If your data has several markers, you either convert them to one marker first or you use several imputers, and later sections show both approaches.
A sentinel value changes what the imputer learns
The first thing to see is the difference between an imputer that knows about the sentinel and one that does not. The column below contains -1 where the value was not recorded.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0], [-1.0], [3.0]])
default = SimpleImputer(strategy="mean").fit(X)
print(default.statistics_) # [1.]
print(default.transform(X).ravel()) # [ 1. -1. 3.]
aware = SimpleImputer(missing_values=-1, strategy="mean").fit(X)
print(aware.statistics_) # [2.]
print(aware.transform(X).ravel()) # [1. 2. 3.]The default imputer finds no NaN, so it fills nothing. Worse, it treats -1 as a real measurement and computes a mean of (1 + -1 + 3) / 3 = 1. The -1 stays in the data, and a downstream model will read it as a real value. The aware imputer excludes -1 from the mean ((1 + 3) / 2 = 2) and then replaces it.
No error or warning is raised in the default case. The pipeline runs and the model trains on corrupted data. This is the most common failure with this parameter, and the only protection is to inspect statistics_ and the transformed output.
Constant fill with a numeric sentinel
You can combine a sentinel with the constant strategy to swap one code for another. In this example -1 marks missing entries, and the imputer replaces them with 0:
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 integer dtype is preserved here because constant does not compute a statistic. With mean or median, scikit-learn converts the data to float, because a mean of integers is generally not an integer.
Text markers in object arrays
String sentinels work the same way. This example uses "?" as the marker and most_frequent to fill it:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["red", "S"],
["?", "M"],
["blue", "?"],
["red", "M"]], dtype=object)
imputer = SimpleImputer(missing_values="?", strategy="most_frequent")
X_filled = imputer.fit_transform(X)
print(imputer.statistics_) # ['red' 'M']
print(X_filled)
# [['red' 'S']
# ['red' 'M']
# ['blue' 'M']
# ['red' 'M']]In column 0, red appears twice and blue once, so red wins. In column 1, M appears twice and S once, so M wins. The "?" entries are excluded from the count, so "?" can never become the most frequent value.
If the strategy is mean or median and the data contains strings, fit raises an error. Those strategies need numeric columns.
Do not confuse sentinels with real values
Using 0 as a marker is the riskiest choice, because zero is often a valid measurement. Consider these columns:
- Income:
0may mean "no income recorded" or a person with genuinely no income. - Blood pressure:
0is physically impossible, so it is safely a marker. - Number of purchases:
0is a legitimate and common value.
The imputer cannot tell the difference. If you declare missing_values=0 on a purchase-count column, every genuine zero is replaced with the column mean, and you have deleted real information. Before you declare a sentinel, look at the data dictionary or the source system, and check the column's value counts. A value that occurs far more often than its neighbors, or that lies outside the physically possible range, is a likely sentinel.
Different markers in different columns
When columns use different conventions, create one imputer per convention and route each to its columns. The ColumnTransformer covered in an earlier chapter handles this:
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
df = pd.DataFrame({
"age": [25, -1, 40, 31],
"income": [40000, 52000, 0, 61000],
})
ct = ColumnTransformer([
("age", SimpleImputer(missing_values=-1, strategy="median"), ["age"]),
("income", SimpleImputer(missing_values=0, strategy="mean"), ["income"]),
])
print(ct.fit_transform(df).tolist())
# [[25.0, 40000.0], [31.0, 52000.0], [40.0, 51000.0], [31.0, 61000.0]]The age imputer ignores -1 and takes the median of 25, 40, 31, which is 31. The income imputer ignores 0 and takes the mean of 40000, 52000, 61000, which is 51000. Each column keeps its own rule, and the rule is stored in the fitted transformer.
Normalizing to NaN before the imputer
Often the cleanest approach is to convert all markers to NaN once, near the point where data enters your code, and then use the default imputer everywhere after. This helps when the data has several markers, and it also keeps the rest of the pipeline simpler, since other tools such as pandas' isna and fillna also understand NaN.
In pandas, read_csv can do the conversion as it loads the file:
import io
import pandas as pd
csv = io.StringIO("age,city\n25,Oslo\n?,Rome\n40,unknown\n")
df = pd.read_csv(csv, na_values=["?", "unknown"])
print(df.isna().sum())
# age 1
# city 1
# dtype: int64For a NumPy float array with more than one numeric marker, use np.isin:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, -1.0],
[-999.0, 4.0],
[3.0, 6.0]])
X_clean = np.where(np.isin(X, [-1, -999]), np.nan, X)
imputer = SimpleImputer(strategy="median")
print(imputer.fit_transform(X_clean))
# [[1. 5.]
# [2. 4.]
# [3. 6.]]This version has a trade-off. The conversion happens outside the scikit-learn pipeline, so you must apply the same conversion to training data, test data, and production data. If the conversion is part of your own code, it must be kept in sync everywhere. When you want a single object that carries all preprocessing, you can wrap the conversion in a FunctionTransformer and place it at the front of a Pipeline, or you can use missing_values and keep the sentinel inside the imputer.
Choosing between the approaches
The following diagram summarizes the decision.
Interactions and edge cases
Real NaN values when the marker is something else
If you set missing_values=-1 and the array also contains real NaN entries, the imputer does not treat the NaN as missing. For non-NaN markers, scikit-learn validates that the input has no non-finite values, so fit raises a ValueError rather than passing the NaN through. Decide on one marker for the data you pass in. If both exist, convert one to the other first.
The indicator uses the same marker
When you set add_indicator=True, the indicator columns record where the entries matched missing_values. The imputer passes its own setting to the indicator, so you do not configure it twice. Later in this tutorial, the chapter on indicator columns builds on this.
Marker consistency between fit and transform
The marker is set when you construct the imputer and applies to every later call. If the test data uses a different convention from the training data, for example -1 in training and NaN in production, the test sentinel will not match. Check that the data sources agree before you reuse a fitted imputer.
Dtype after substitution
With mean and median, the output is a float array even if the input was integer. With constant and most_frequent, the dtype can stay as it was, which matters when a column of integer codes should remain integers.
Data in DataFrames
When you pass a DataFrame, the imputer converts it to an array first. Mixed-type frames therefore become object arrays unless you split numeric and categorical columns with a ColumnTransformer. A -1 in a numeric column and "?" in a text column cannot share one imputer, which is another reason to route columns separately.
Checklist before you trust the output
- Find the real marker. Look at
df.describe(),value_counts(), and the data documentation. - Check that the marker cannot also be a valid value in the same column.
- Set
missing_valuesto that marker, or convert it toNaNearlier. - Fit the imputer and print
statistics_. Compare at least one entry with a hand calculation. - Transform a small sample and confirm that no sentinel remains, for example with
(X_out == marker).sum().
Exercise
A column of sensor readings uses -999.0 for "sensor offline". You fit SimpleImputer(strategy="mean") with no other arguments on the training data and get a mean of -120.4, which is far outside the sensor's normal range of 10 to 40. What went wrong, and how do you fix it?
Show answer
The default missing_values=np.nan does not recognize -999.0, so the imputer treats those entries as real readings. They are included in the mean, which pulls it far below the normal range, and they are never replaced. Fix it by setting missing_values=-999.0 (or converting -999.0 to np.nan before imputing), refitting, and checking that statistics_ now falls between 10 and 40.
Exercise
A dataset has an "age" column where -1 means missing, and a "children" column where 0 is a valid count but -1 also means missing. A teammate suggests a single SimpleImputer(missing_values=0, strategy="median") for both columns. Give two reasons this is wrong.
Show answer
First, the marker is wrong for both columns: the sentinel is -1, not 0, so the -1 entries would stay in the data and distort the median. Second, 0 is a valid value in the "children" column, so the imputer would replace real zeros with the median and destroy genuine information. A correct setup uses missing_values=-1 for both columns, which works because both use -1 as the marker. The imputer is then safe for "children" because 0 is no longer treated as missing.
Exercise
Your data contains the markers "?" and "unknown" in a text column, both meaning "not recorded". SimpleImputer accepts only one missing_values value. Describe two ways to handle this.
Show answer
Option 1: convert both markers to NaN before the imputer, for example with pd.read_csv(..., na_values=["?", "unknown"]) or df.replace(["?", "unknown"], np.nan), then use the default imputer with most_frequent or constant. Option 2: apply a first step that rewrites one marker to the other (for example "unknown" to "?") and then set missing_values="?". Option 1 is usually clearer because NaN works with the rest of pandas and scikit-learn.