Sub topic 8
Keeping the missingness signal with indicator columns
This chapter assumes you can already fit a SimpleImputer and read its statistics_ attribute. It also assumes you know why imputers must be fitted on training data only, and that you have used Pipeline and ColumnTransformer. Here you will learn what add_indicator=True does, how it behaves on new data, and when the extra columns help a model.
Why imputation destroys information
Imputation makes a matrix usable, but it also hides something. After a mean imputer runs, a row whose age was missing looks like a row whose age happened to equal the average. The model cannot tell the two apart.
That matters when the fact that a value is missing carries information about the target. Some examples:
- A loan applicant leaves "previous defaults" blank because they have none, or because they would rather not say.
- A sensor stops reporting just before a machine fails.
- A patient has no lab result because the doctor judged the test unnecessary.
Statisticians call the process that decides which values go missing the missingness mechanism. The three standard cases are:
| Mechanism | Meaning | Does an indicator column help? |
|---|---|---|
| Missing completely at random (MCAR) | Missingness is unrelated to any value, observed or not | Rarely. It adds noise columns. |
| Missing at random (MAR) | Missingness depends on other observed columns | Sometimes. The other columns may already explain it. |
| Missing not at random (MNAR) | Missingness depends on the missing value itself, or on something unobserved | Often. The indicator is the only trace of that signal. |
You cannot prove from the data alone which mechanism you have. The practical way to decide is to try both variants under cross-validation, as shown later in this chapter.
What add_indicator does
SimpleImputer has a parameter add_indicator that defaults to False. When you set it to True, the imputer builds a second set of columns. Each one holds 1 where the original entry was missing and 0 where it was present. These columns are appended to the right of the imputed columns.
Internally the imputer owns a MissingIndicator object, stored in the indicator_ attribute. During fit, it learns which columns contained missing values. During transform, it emits one binary column for each of those columns.
A first example
This example uses the same matrix as earlier chapters, with the mean strategy.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, np.nan]])
imputer = SimpleImputer(strategy="mean", add_indicator=True)
X_out = imputer.fit_transform(X)
print(imputer.statistics_.tolist()) # [4.0, 2.5]
print(imputer.indicator_.features_.tolist()) # [0, 1]
print(X_out.tolist())
# [[1.0, 2.0, 0.0, 0.0], [4.0, 3.0, 1.0, 0.0], [7.0, 2.5, 0.0, 1.0]]
print(imputer.get_feature_names_out().tolist())
# ['x0', 'x1', 'missingindicator_x0', 'missingindicator_x1']The output has four columns instead of two. The first two are the imputed values. Column 2 flags that the first feature was missing in row 1, and column 3 flags that the second feature was missing in row 2.
Two attributes tell you what the imputer learned. statistics_ holds the fill value per column. indicator_.features_ holds the positions of the input columns that get an indicator. The feature names carry the prefix missingindicator_, so you can tell the two kinds of column apart after the fact.
Indicators only for columns that had missing values at fit time
By default, the indicator uses features="missing-only". It creates a column only for features that contained at least one missing value during fit. Columns that were complete in the training data get no indicator. The set is fixed at fit time and is not recomputed on new data.
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, 4.0]])
imputer = SimpleImputer(strategy="mean", add_indicator=True)
print(imputer.fit_transform(X_train).tolist())
# [[1.0, 2.0, 0.0], [4.0, 3.0, 1.0], [7.0, 4.0, 0.0]]
print(imputer.indicator_.features_.tolist()) # [0]
X_new = np.array([[np.nan, np.nan]])
print(imputer.transform(X_new).tolist())
# [[4.0, 3.0, 1.0]]The training data had no missing values in column 1, so no indicator exists for it. In X_new, column 1 is missing, and the imputer fills it with the training mean 3.0. It adds no flag, because the output width is fixed at three columns. The imputer does not raise an error. The fill still happens, but the "this was missing" signal for that column is lost.
Seeing the effect on a model
The next experiment builds a case where missingness is the only predictive signal. The feature x is pure noise. But when y is 1, x is deleted 80 percent of the time.
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
n = 1000
y = rng.integers(0, 2, size=n)
x = rng.normal(size=n)
x[(y == 1) & (rng.random(n) < 0.8)] = np.nan
X = x.reshape(-1, 1)
for add_indicator in (False, True):
model = make_pipeline(
SimpleImputer(strategy="mean", add_indicator=add_indicator),
LogisticRegression(),
)
scores = cross_val_score(model, X, y, cv=5)
print(add_indicator, round(scores.mean(), 2))
# False: roughly 0.5, no better than guessing
# True: roughly 0.9Without the indicator, every imputed row has the same value, the training mean. The observed values of x say nothing about y, so accuracy stays near chance. With the indicator, a missing entry predicts class 1 with certainty. The rows that are present are mostly class 0, so the model reaches about 0.9. The exact numbers depend on the random draw, but the gap is large.
Real data is rarely this clean. The experiment shows the mechanism, but you should measure the gain on your own data.
Fixed-width indicators with MissingIndicator
MissingIndicator can also be used on its own. Its features parameter controls which columns get an output column:
"missing-only"(the default) emits columns only for features that had missing values during fit."all"emits one column per input feature, so the width never changes.
import numpy as np
from sklearn.impute import MissingIndicator, SimpleImputer
from sklearn.pipeline import make_union
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, 4.0]])
print(MissingIndicator(features="all").fit_transform(X).tolist())
# [[False, False], [True, False], [False, False]]
both = make_union(SimpleImputer(strategy="mean"),
MissingIndicator(features="all"))
print(both.fit_transform(X).tolist())
# [[1.0, 2.0, 0.0, 0.0], [4.0, 3.0, 1.0, 0.0], [7.0, 4.0, 0.0, 0.0]]The union stacks the imputed matrix and the indicator matrix side by side. This keeps the output width equal to twice the input width, whatever the data looks like. It also lets you choose a different configuration for the indicator than for the imputer.
The two approaches compare as follows:
| Approach | Output width | Indicator for columns complete in training | Best for |
|---|---|---|---|
| `SimpleImputer(add_indicator=True)` | Depends on the training data | No | Compact models, quick experiments |
| `MissingIndicator(features="all")` in a union | Always twice the input width | Yes | Production pipelines where the schema must not change |
The indicator follows missing_values
The indicator uses the same missing_values setting as the imputer. If you declared -1 as the missing marker, the indicator flags the -1 entries, not NaN.
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, add_indicator=True)
print(imputer.fit_transform(X).tolist())
# [[1, 0, 0, 1], [0, 4, 1, 0], [3, 6, 0, 0]]Both columns had a sentinel in training, so both get an indicator. The output stays integer because the input was integer.
Indicators inside a ColumnTransformer
In a real project you will usually switch the indicator on only for the numeric columns. This pipeline imputes numbers with the median and adds indicators. It fills missing cities with the explicit category "missing".
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [25, np.nan, 40, 31, 52, np.nan],
"income": [40000, 52000, np.nan, 61000, 75000, 48000],
"city": ["Oslo", "Rome", np.nan, "Oslo", "Rome", "Oslo"],
})
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median", add_indicator=True)),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="missing")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
Xt = preprocess.fit_transform(df)
print(Xt.shape) # (6, 7)
print(preprocess.get_feature_names_out().tolist())
# ['num__age', 'num__income', 'num__missingindicator_age',
# 'num__missingindicator_income', 'cat__city_Oslo',
# 'cat__city_Rome', 'cat__city_missing']Four details are worth noticing:
- The numeric branch produces four columns: two imputed, two indicators.
- The scaler runs after the imputer, so it also rescales the indicator columns. A 0/1 column becomes two other numbers. Predictions are unaffected for a linear model, but a coefficient on a scaled indicator no longer reads as "the effect of being missing". If you want raw 0/1 flags, put a separate
MissingIndicatorbranch in theColumnTransformer. - The categorical branch uses
fill_value="missing"instead ofadd_indicator. For categorical data this is the better tool. The one-hot encoder turns it into acity_missingcolumn, which is already an indicator, and the extra 0/1 column would be redundant. An indicator column appended next to string values would also produce a mixed-type array thatOneHotEncoderwould then encode as categories, which is rarely what you want. - The whole object is a single unit. Append
("clf", LogisticRegression())in aPipelineand cross-validation refits the imputer, includingfeatures_, on every training fold.
Common errors
- Expecting an indicator for every column. Columns without missing values in the training data get none. Check
indicator_.features_. - Indexing columns by position after transform. Indicators are appended at the end, and their count depends on the training data. Use feature names, not integer positions.
- Assuming a fixed schema across retrains. If last month's data had no NaN in a column and this month's does, the output width changes. Models and downstream code that depend on width will break.
features="all"avoids this. - Adding indicators to everything by default. Each indicator is an extra feature. With hundreds of sparse columns, you may add hundreds of noisy features and slow training.
- Computing the indicator outside the pipeline. If you build indicators on the full dataset before splitting, the choice of which columns get one is informed by the test rows. The effect is small, but keeping it inside the pipeline removes the question.
When indicators help and when they do not
Use an indicator when:
- You suspect missingness depends on the target or on the hidden value (MNAR).
- The model is linear or otherwise cannot see missingness on its own.
- Cross-validation shows a gain.
Skip it when:
- Missingness is clearly random, such as a random transmission failure.
- The model handles missing values itself.
HistGradientBoostingClassifierandHistGradientBoostingRegressoraccept NaN directly and learn which side of each split missing values go to. - You have many columns with missing values and little data. Several columns often go missing together, which makes the indicators nearly identical copies of each other.
The evidence should come from your data. Run the same cross-validation twice, once with add_indicator=False and once with True, and keep the extra columns only if the score improves by more than the fold-to-fold variation.
Exercise
A SimpleImputer(strategy="mean", addindicator=True) is fitted on Xtrain = [[1, nan], [2, 5], [3, 7]]. It then transforms [[nan, nan]]. What are statistics, indicator.features_ and the output?
Show answer
statistics is [2., 6.]. indicator.features_ is [1], because only column 1 had a missing value during fit. The output is [[2.0, 6.0, 1.0]]: both entries are filled with the training means, but only column 1 has an indicator, and its flag is 1. Column 0 gets no flag even though it is missing in the new row.
Exercise
Your production data sometimes has NaN in columns that were complete in training, and you want a flag for those too. What do you change, and what is the cost?
Show answer
Replace addindicator=True with a union of the imputer and MissingIndicator(features="all"), for example makeunion(SimpleImputer(strategy="median"), MissingIndicator(features="all")). Every input column then gets an indicator regardless of training data, so the schema is stable. The cost is that the output width doubles, including indicators for columns that may never be missing.
Exercise
In the ColumnTransformer example, why is the categorical column filled with fillvalue="missing" instead of using addindicator=True?
Show answer
The constant "missing" becomes its own category, and OneHotEncoder turns it into a citymissing column, which already serves as an indicator. Adding addindicator would append a redundant 0/1 column and mix numbers with strings in one array. That mixed array would be one-hot encoded as if its values were categories.