Sub topic 1
Why Missing Values Need Handling
Prerequisites
This chapter assumes you know:
- Basic Python and NumPy arrays
- pandas DataFrames
- The scikit-learn estimator pattern:
fit,transform,predict - The difference between training data and test data
You do not need to know anything about imputation yet. This chapter explains why it is needed. The next chapters show how to do it with SimpleImputer.
What NaN represents
Real datasets often have gaps. A survey respondent skips a question. A sensor drops a reading. A join between two tables finds no match. In a feature matrix, the table of input values a model learns from, these gaps are usually stored as NaN.
NaN stands for "not a number". It is a special floating-point value defined by the IEEE 754 standard. NumPy and pandas use it as their default marker for a missing entry. Because NaN is a float, a NumPy array that contains it must have a float dtype.
import numpy as np
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, np.nan]])
print(X.dtype) # float64
print(np.isnan(X))
# [[False False]
# [ True False]
# [False True]]
print(np.isnan(X).sum(axis=0)) # [1 1]Note that NaN does not equal anything, not even itself. np.nan == np.nan is False. Use np.isnan or pandas.isna to find missing entries. Never compare with ==.
Why estimators fail on NaN
Most scikit-learn estimators do math on every entry. A linear model multiplies each feature by a weight and sums the results. Any sum that includes NaN becomes NaN. Distance-based models, scalers, and many other estimators have the same problem.
To protect you from silent garbage, scikit-learn checks the input first. If it finds NaN, it raises an error:
import numpy as np
from sklearn.linear_model import LogisticRegression
X = np.array([[1.0, 2.0],
[np.nan, 3.0],
[7.0, 4.0],
[5.0, 1.0]])
y = [0, 1, 0, 1]
try:
LogisticRegression().fit(X, y)
except ValueError as error:
print(error)
# Input X contains NaN.
# LogisticRegression does not accept missing values encoded as NaN natively. ...The message names the estimator and suggests alternatives. A few estimators, such as HistGradientBoostingClassifier, accept NaN natively and learn how to route missing entries. These are the exception. For most of the library you must handle missing values yourself before fitting.
Your options
There are three common ways to deal with missing values.
| Option | What it does | Main cost |
|---|---|---|
| Drop rows | Remove every row that has a gap | Loses data, and can bias the sample if gaps are not random |
| Drop columns | Remove every feature with gaps | Loses a feature that may be informative |
| Impute | Fill each gap with a substitute value | The substitute is a guess, so it can distort the data |
Dropping rows is simple, but it can discard most of a dataset. If 5 columns each miss 10% of their values at random, only about 59% of rows are complete (0.9^5). Imputation keeps every row. This tutorial focuses on imputation.
Imputation means replacing a missing entry with an estimated value. The simplest estimates come from the column itself, such as its mean. SimpleImputer is scikit-learn's tool for these column-based estimates.
Where imputation fits in a workflow
Imputation is a preprocessing step. It runs after you load and inspect the data, and before the model sees it. The imputer learns something from the data (for example, a column mean), so it follows the same fit and transform pattern you already know.
The learned statistic matters. If you compute it from all your data before splitting into training and test sets, information from the test set leaks into training. A later chapter covers this in detail. For now, remember that imputation is learned, not just applied.
Why the pattern of missingness matters
Statisticians describe three kinds of missingness:
- Missing completely at random: the gap has no relation to any data. A sensor fails at random times.
- Missing at random: the gap depends on other observed columns. Younger respondents skip an income question more often, and age is recorded.
- Missing not at random: the gap depends on the missing value itself. People with very high incomes decline to report income.
Simple imputation works best in the first case. In the other two, filling gaps with a column average can hide a real pattern. Later chapters show how to keep that signal with indicator columns, and the final chapter points to model-based imputers for harder cases.
Checking your own data
Before choosing any method, measure how much is missing and where.
import numpy as np
import pandas as pd
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"],
})
print(df.isna().sum())
# age 2
# income 1
# city 1
# dtype: int64
print(df.isna().mean().round(2))
# age 0.33
# income 0.17
# city 0.17
# dtype: float64
print(df.dropna().shape) # (3, 3)Dropping incomplete rows here leaves 3 of 6 rows. That is a typical reason to impute instead.
Exercise
A column has 40% missing values, and you call LogisticRegression().fit(X, y) on the raw data. What happens, and why is dropping every row with a gap a risky fix?
Show answer
The call raises a ValueError because LogisticRegression does not accept NaN values. Dropping rows with gaps can remove a large share of the data. If the gaps are not random, the remaining rows are also a biased sample of the population. Imputing keeps all rows.
Exercise
Why is X == np.nan the wrong way to find missing entries in a NumPy array? Name a correct alternative.
Show answer
NaN is never equal to anything, including itself, so the comparison is False everywhere. Use np.isnan(X) for arrays or df.isna() for pandas objects.