Handling Missing Data
Real data has holes: a sensor was offline, a customer skipped a form field, a value was lost when merging two tables. Most scikit-learn models refuse to train on missing values (NaN) and raise an error. You need a strategy.
Finding missing values
In pandas, missing values appear as NaN (or None/NaT). isna() finds them:
import io
import pandas as pd
csv = """age,income,city,owns_car
34,52000,Leeds,yes
,61000,York,no
45,,Leeds,yes
29,38000,,no
51,75000,York,
38,,Hull,yes
26,41000,Hull,no"""
df = pd.read_csv(io.StringIO(csv))
print(df)
print()
print("missing per column:")
print(df.isna().sum())
print("rows with any missing value:", int(df.isna().any(axis=1).sum()), "of", len(df)) age income city owns_car
0 34.0 52000.0 Leeds yes
1 NaN 61000.0 York no
2 45.0 NaN Leeds yes
3 29.0 38000.0 NaN no
4 51.0 75000.0 York NaN
5 38.0 NaN Hull yes
6 26.0 41000.0 Hull no
missing per column:
age 1
income 2
city 1
owns_car 1
dtype: int64
rows with any missing value: 5 of 7
Empty fields in a CSV become NaN automatically. Note that a column of whole numbers with a missing value becomes float64, since NaN is a float.
Option 1: drop
The simplest strategy is to remove rows (or columns) with missing values:
import io
import pandas as pd
csv = """age,income,city,owns_car
34,52000,Leeds,yes
,61000,York,no
45,,Leeds,yes
29,38000,,no
51,75000,York,
38,,Hull,yes
26,41000,Hull,no"""
df = pd.read_csv(io.StringIO(csv))
print("dropna():", df.dropna().shape)
print("dropna(subset=['income']):", df.dropna(subset=["income"]).shape)
print("drop columns with > 20% missing:", df.loc[:, df.isna().mean() <= 0.2].columns.tolist())dropna(): (2, 4)
dropna(subset=['income']): (5, 4)
drop columns with > 20% missing: ['age', 'city', 'owns_car']
Dropping is fine when only a few rows are affected. Here it would throw away more than half of the data — usually too expensive. Also, you can't drop rows at prediction time: a new customer with a missing field still needs a prediction.
Option 2: impute
Imputation fills each gap with a plausible value. scikit-learn's SimpleImputer learns a fill value per column during fit and applies it during transform, exactly like a scaler:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[34, 52000],
[np.nan, 61000],
[45, np.nan],
[29, 38000],
[51, 75000],
[38, np.nan],
[26, 41000]])
for strategy in ["mean", "median"]:
imp = SimpleImputer(strategy=strategy).fit(X)
print(f"{strategy:6} fill values: {imp.statistics_.round(1).tolist()}")
filled = SimpleImputer(strategy="median").fit_transform(X)
print(filled.astype(int)) # whole numbers print more neatlymean fill values: [37.2, 53400.0]
median fill values: [36.0, 52000.0]
[[ 34 52000]
[ 36 61000]
[ 45 52000]
[ 29 38000]
[ 51 75000]
[ 38 52000]
[ 26 41000]]
| Strategy | Fills with | Good for |
|---|---|---|
"mean" |
column mean | roughly symmetric numbers |
"median" |
column median | skewed numbers, outliers |
"most_frequent" |
most common value | categories |
"constant" |
a value you choose (fill_value=) |
e.g. "unknown" for text, 0 for counts |
For categorical columns use most_frequent or constant:
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
cities = pd.DataFrame({"city": ["Leeds", "York", "Leeds", np.nan, "York", "Hull", "Leeds"]})
print(SimpleImputer(strategy="most_frequent").fit_transform(cities).ravel())
print(SimpleImputer(strategy="constant", fill_value="unknown").fit_transform(cities).ravel())['Leeds' 'York' 'Leeds' 'Leeds' 'York' 'Hull' 'Leeds']
['Leeds' 'York' 'Leeds' 'unknown' 'York' 'Hull' 'Leeds']
Keep the information that a value was missing
Sometimes the fact that a value is missing is informative (customers who hide their income may behave differently). add_indicator=True appends a 0/1 column per feature that had missing values:
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[34, 52000], [np.nan, 61000], [45, np.nan], [29, 38000]])
imp = SimpleImputer(strategy="median", add_indicator=True)
print(imp.fit_transform(X).astype(int))
print(imp.get_feature_names_out(["age", "income"]))[[ 34 52000 0 0]
[ 34 61000 1 0]
[ 45 52000 0 1]
[ 29 38000 0 0]]
['age' 'income' 'missingindicator_age' 'missingindicator_income']
Smarter imputation
KNNImputer fills a gap with the average of the most similar rows (based on the other features), which often beats a single column-wide value:
import numpy as np
from sklearn.impute import KNNImputer
# columns: house size (m2), rooms, price (thousands)
X = np.array([[50, 2, 210],
[52, 2, np.nan],
[120, 5, 480],
[118, 5, 470],
[80, 3, 320],
[125, np.nan, 495]])
filled = KNNImputer(n_neighbors=2).fit_transform(X)
print(filled.round(1))[[ 50. 2. 210.]
[ 52. 2. 265.]
[120. 5. 480.]
[118. 5. 470.]
[ 80. 3. 320.]
[125. 5. 495.]]
The missing price of the 52 m² flat is the average of its two nearest neighbours (the 50 m² and 80 m² flats), not the overall mean, which the big houses would have inflated. Similarly the missing room count comes from the two most similar large houses.
Warning: Fit imputers on the training data only, then transform the test data with the same fitted imputer — otherwise information from the test set leaks into training. Putting the imputer inside a pipeline (next lessons) handles this automatically. Some models, such as
HistGradientBoostingClassifier, acceptNaNdirectly.
Go further: KNN and Iterative Imputation fills a value from the other columns, fitted on the training part only.
Test yourself
Which imputation strategy is most robust to outliers for a numeric column?
- mean
- median
- constant 0
- most_frequent
What does SimpleImputer(add_indicator=True) add?
- A column with row numbers
- 0/1 columns marking where values were missing
- A column of means
- Nothing
Why is dropping rows often a poor strategy?
- It is slow
- It can discard a lot of data, and new samples at prediction time may still have gaps
- pandas cannot drop rows
- It changes the column names