Sub topic 9
Edge cases: empty columns, dtypes and feature names
This chapter assumes you have used SimpleImputer with fit, transform and statistics_, and that you have seen it inside a ColumnTransformer. It covers three situations that tend to cause confusing bugs: columns with no observed values, data types the chosen strategy cannot handle, and column names after imputation.
Columns that are entirely missing
The imputer computes each fill value from the observed entries of a column. A column with no observed entries has nothing to compute from. By default, SimpleImputer drops such a column from the output and warns you.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, np.nan],
[2.0, np.nan],
[np.nan, np.nan]])
imputer = SimpleImputer(strategy="mean")
out = imputer.fit_transform(X)
print(imputer.statistics_) # [1.5 nan]
print(out.shape) # (3, 1)The learned statistics_ still has two entries, and the second is nan. The output has only one column. The imputer only drops columns that were empty during fit. A column that was empty at fit time but has values at transform time is still dropped.
Dropping a column changes the output width. This breaks any code that indexes columns by position after imputation. To keep the shape stable, set keep_empty_features=True (available since scikit-learn 1.2).
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0, np.nan],
[2.0, np.nan],
[np.nan, np.nan]])
imputer = SimpleImputer(strategy="mean", keep_empty_features=True)
print(imputer.fit_transform(X))
# [[1. 0. ]
# [2. 0. ]
# [1.5 0. ]]The empty column is filled with 0. With strategy="constant", it is filled with fill_value instead. A constant column carries no information, so many models ignore it. It is still worth keeping when a later step expects a fixed number of columns.
Dtypes and strategies
The strategy determines which dtypes are allowed.
| Strategy | Numeric columns | String or object columns |
|---|---|---|
| `mean` | Yes | No, raises `ValueError` |
| `median` | Yes | No, raises `ValueError` |
| `most_frequent` | Yes | Yes |
| `constant` | Yes | Yes, if `fill_value` is a string |
The numeric strategies convert the input to floating point, so an integer array comes out as floats. The most_frequent and constant strategies keep the original dtype where they can. That is why the integer example in an earlier chapter returned integers.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["red"], [np.nan], ["blue"], ["red"]], dtype=object)
print(SimpleImputer(strategy="most_frequent").fit_transform(X))
# [['red']
# ['red']
# ['blue']
# ['red']]
try:
SimpleImputer(strategy="mean").fit_transform(X)
except ValueError as err:
print(type(err).__name__) # ValueErrorIn a ColumnTransformer, this is the main reason to route numeric and categorical columns through separate imputers. A single mean imputer applied to a mixed table fails on the first text column.
When you use constant with a numeric column, choose a fill_value that fits the dtype. A string fill value in a numeric column raises an error at fit time.
Feature names after imputation
When you fit on a pandas DataFrame, the imputer records the input column names. get_feature_names_out() returns the names of the columns that actually come out, which already accounts for dropped empty columns.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({"a": [1.0, np.nan, 3.0],
"c": [4.0, 5.0, 6.0]})
imputer = SimpleImputer(strategy="mean", add_indicator=True)
imputer.fit(df)
print(imputer.get_feature_names_out())
# ['a' 'c' 'missingindicator_a']The output has the imputed columns first, then one indicator column for each feature that had missing values at fit time. Column c had none, so it gets no indicator. Reading these names is the quickest way to check what a transformer produced.
To get a DataFrame back instead of a NumPy array, call set_output.
imputer.set_output(transform="pandas")
print(imputer.transform(df))This keeps the column names and the original index. It works on a whole Pipeline or ColumnTransformer too, which makes the final matrix easier to inspect.
Common errors
- A shape mismatch after imputation. A column was empty at fit time and was dropped. Check for the warning, then use
keep_empty_features=Trueor remove the column before fitting. ValueErrorabout non-numeric data. You usedmeanormedianon text. Switch tomost_frequentorconstant.- Wrong column order in a hand-built array. Indicator columns are appended at the end. Use
get_feature_names_out()rather than counting positions. - Fill values that look off. Print
statistics_and confirm it has nonanentries. Ananmeans that column was empty during fit.
Exercise
You fit SimpleImputer(strategy="median") on a DataFrame with three columns, and one column is entirely NaN in the training data. At transform time you get two columns instead of three, and a downstream step that expects three fails. Give two ways to fix this and say what the empty column holds in each.
Show answer
Set keepemptyfeatures=True, so the empty column is kept and filled with 0 (or with fill_value if the strategy is "constant"). Alternatively, drop the empty column from the training data before fitting, so every later step is built for two columns. The first keeps the width fixed but adds a constant column. The second removes a column that carries no information.