Sub topic 9
Edge cases: empty columns, dtypes and feature names
This chapter covers the situations where SimpleImputer behaves in ways the basic examples don't show. It looks at columns with no observed values, the effect of input dtype, and how output columns are named and counted. I assume you can fit and transform with SimpleImputer, read statistics_, and build a ColumnTransformer and Pipeline, as in the earlier chapters. The examples use scikit-learn 1.2 or later, because they rely on keep_empty_features and set_output.
Columns with no observed values
The imputer learns each fill value from the non-missing entries of a column. If every entry is missing, the mean, median and most_frequent strategies have nothing to compute from.
By default, scikit-learn records NaN as that column's statistic and then drops the column from the output.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, np.nan, 3.0],
[4.0, np.nan, np.nan],
[7.0, np.nan, 9.0]])
imputer = SimpleImputer(strategy="mean")
X_out = imputer.fit_transform(X)
print(imputer.statistics_) # [ 4. nan 6.]
print(X_out.shape) # (3, 2)
print(X_out)
# [[1. 3.]
# [4. 6.]
# [7. 9.]]The input has three columns and the output has two. The middle column is gone, and statistics_ still has three entries. The NaN in statistics_ marks the dropped column.
Keeping empty columns
Setting keep_empty_features=True keeps the column. The imputer fills it with 0. With strategy="constant" it fills it with fill_value.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, np.nan, 3.0],
[4.0, np.nan, np.nan],
[7.0, np.nan, 9.0]])
imputer = SimpleImputer(strategy="mean", keep_empty_features=True)
print(imputer.fit_transform(X))
# [[1. 0. 3.]
# [4. 0. 6.]
# [7. 0. 9.]]
print(imputer.statistics_) # [4. 0. 6.]The constant strategy never drops columns. Its statistics are fill_value for every column, so no column ever has an NaN statistic.
Which behavior should you choose?
The right choice depends on why the column is empty.
- The column is empty in the full dataset. It carries no information, so dropping it is usually correct.
- The column is empty only in one cross-validation training fold. A column that is dropped in one fold and kept in another can produce models with different input widths. Inside a
Pipeline, each fold is fitted separately, so this is consistent within a fold. It still makes the folds harder to compare. - A downstream step needs a fixed number of columns, for example a model whose input size is set in advance. Use
keep_empty_features=True.
A column that is only partly empty
A column can have observed values at fit time and be entirely NaN at transform time. This causes no problem. The fill value comes from statistics_, which was learned at fit time, so every missing entry is replaced.
The reverse case matters more. A column that was all NaN at fit time and was dropped stays dropped. Observed values in the new data do not bring it back.
How the input dtype changes the result
SimpleImputer treats numeric and non-numeric data differently, and the dtype of the input array affects the dtype of the output.
| Input dtype | `mean` / `median` | `most_frequent` | `constant` | Output dtype |
|---|---|---|---|---|
| float | works | works | works | float |
| int | works, converts to float | works | works | float for `mean` and `median`, int otherwise |
| object or string | `ValueError` | works | works | object |
Integer arrays cannot hold NaN. They only contain missing entries when you use a sentinel value and set missing_values. For mean and median, the imputer converts the input to float, because a mean is usually not a whole number.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1, -1],
[-1, 4],
[3, 6]])
imputer = SimpleImputer(missing_values=-1, strategy="mean")
X_out = imputer.fit_transform(X)
print(imputer.statistics_) # [2. 5.]
print(X_out.dtype) # float64
print(X_out)
# [[1. 5.]
# [2. 4.]
# [3. 6.]]With most_frequent or constant, an integer input stays integer, which is what the earlier constant example showed.
Strings and the numeric-only strategies
The mean and median strategies reject text. The error tells you the strategy is the problem.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["red"], [np.nan], ["blue"]], dtype=object)
try:
SimpleImputer(strategy="mean").fit(X)
except ValueError as err:
print(str(err).splitlines()[0])
# Cannot use mean strategy with non-numeric data:
imputer = SimpleImputer(strategy="most_frequent")
print(imputer.fit_transform(X).tolist())
# [['red'], ['blue'], ['blue']]The most_frequent result needs one more explanation. "red" and "blue" each appear once, so they tie. When several values tie for most frequent, the imputer picks the smallest. For strings this means the first in sorted order, which is "blue". The tie-break is deterministic, but it is arbitrary. If ties are likely in your data, for example with small categories or a small training fold, consider whether the filled value is meaningful.
The default fill_value
When you use strategy="constant" without fill_value, the default depends on the data. Numeric data gets 0. String or object data gets the string "missing_value".
If you pass a fill_value that does not suit the data, you get an error. For numeric data, a string fill_value raises a ValueError saying a numerical value is expected.
Mixed DataFrames
A DataFrame with both numeric and text columns is converted to an object array when you pass it to a single imputer. The mean strategy then fails because of the text columns. The fix is the one from the pipeline chapter. Use a ColumnTransformer so each imputer sees only columns of one kind.
Sparse input
SimpleImputer accepts SciPy sparse matrices, with one restriction. Sparse matrices store zeros implicitly, so missing_values=0 would mean "every implicit entry is missing". scikit-learn refuses this and raises a ValueError asking for a dense array. If your sentinel is 0, convert to a dense array first, or choose a different encoding upstream.
Output type and column names
By default, transform returns a NumPy array, even when you pass in a DataFrame. Column names and the index are lost. Two tools keep them.
set_output
Since version 1.2, set_output(transform="pandas") makes a transformer return a DataFrame. It keeps the index and uses the column names reported by get_feature_names_out().
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({
"age": [25, np.nan, 40],
"empty": [np.nan, np.nan, np.nan],
"income": [40000, 52000, np.nan],
}, index=["a", "b", "c"])
imputer = SimpleImputer(strategy="median").set_output(transform="pandas")
out = imputer.fit_transform(df)
print(out.columns.tolist()) # ['age', 'income']
print(out.index.tolist()) # ['a', 'b', 'c']
print(out.loc["b", "age"]) # 32.5The output has no empty column, and the remaining columns keep their names. The median of age is the average of 25 and 40, which is 32.5.
get_feature_names_out
get_feature_names_out() returns the names of the output columns. It accounts for dropped columns, so it is the reliable way to know what the output contains.
If you fit the imputer on a DataFrame, it stores feature_names_in_ and uses it. If you fit it on a plain array, the names are generated as x0, x1 and so on. You can also pass input_features explicitly.
Names when add_indicator is on
With add_indicator=True, the indicator columns are appended after the imputed columns. Their names start with missingindicator_.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({
"age": [25, np.nan, 40],
"empty": [np.nan, np.nan, np.nan],
"income": [40000, 52000, np.nan],
})
imputer = SimpleImputer(strategy="median", add_indicator=True)
imputer.set_output(transform="pandas")
out = imputer.fit_transform(df)
print(out.columns.tolist())
# ['age', 'income', 'missingindicator_age', 'missingindicator_empty', 'missingindicator_income']
print(out.shape) # (3, 5)Two details are worth noting here.
- The indicator is computed from the original input, not from the imputed output. So
missingindicator_emptyexists even though theemptycolumn itself was dropped. An all-missing column leaves behind a column of ones. - The indicator uses
features="missing-only". It creates columns only for features that had missing values in the training data. A column with no missing values at fit time gets no indicator. If missing values show up in that column later, nothing records them. The output width is fixed at fit time.
Names inside a ColumnTransformer
In a ColumnTransformer, names get a prefix from the transformer name, and nested pipelines work as long as every step supports get_feature_names_out. A fitted version of the earlier pipeline shows this.
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")),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
preprocess.fit(df)
print(preprocess.get_feature_names_out().tolist())
# ['num__age', 'num__income', 'cat__city_Oslo', 'cat__city_Rome']Each name has the transformer's prefix. The one-hot encoder adds the category after the column name. If one of the numeric columns were all missing, num__ would simply list one fewer name, and the output would be narrower with no error.
Checking inputs at transform time
At transform, the imputer compares the input against what it saw during fit.
- The number of columns must match
n_features_in_. A different count raises aValueError. This applies to the input count. The output may be narrower because of dropped columns, but the input must have the same number of columns as at fit time. - If you fit on a DataFrame, the column names and their order must match
feature_names_in_. Reordered or renamed columns raise aValueError. This check protects you from imputing the age column with the income median. - New data may contain
NaNin columns that had none during fit. Those entries are filled with the learned statistic, but no indicator column exists for them, as described above.
A checklist for edge cases
- Look at
statistics_after fitting. AnNaNentry means that column will be dropped. - Compare
X_out.shape[1]withX.shape[1], or printget_feature_names_out(). - Check the dtypes of your columns before you pick
meanormedian. Use aColumnTransformerto separate numeric from text columns. - For integer data with a sentinel, set
missing_valuesand expect float output frommeanandmedian. - Decide whether ties in
most_frequentmatter for your data. - Use
set_output(transform="pandas")when you want names and index to survive.
Exercise
You fit SimpleImputer(strategy="median") on a training array with 4 columns. The third column is entirely NaN. transform returns an array with 3 columns. What is statistics_[2], and which single parameter change makes the output have 4 columns again? What value will the third column contain?
Show answer
statistics_[2] is nan, which marks the column as having no observed values, so it is dropped. Setting keep_empty_features=True keeps the column. The imputer fills it with 0, and statistics_[2] becomes 0.
Exercise
A DataFrame has a numeric column age with missing values and a text column city with missing values. Calling SimpleImputer(strategy="mean").fit(df) raises a ValueError. Why, and how do you impute both columns correctly?
Show answer
The mean strategy cannot handle non-numeric data, and the single imputer sees the whole DataFrame, including city. Use a ColumnTransformer with a SimpleImputer(strategy="mean") or "median" for age and a SimpleImputer(strategy="most_frequent") (or "constant") for city.
Exercise
An imputer with add_indicator=True is fitted on data where column B has no missing values. At prediction time, column B contains a missing value. What happens to that value, and is there an indicator column for it?
Show answer
The value is filled with the median or mean learned at fit time. There is no indicator column for B, because the indicator only covers features that had missing values during fit (features="missing-only"). The output width stays the same as it was at fit time.