Sub topic 4
Cleaning data and handling missing values
This chapter assumes you can read pandas DataFrames, know what a train/test split is, and have seen a scikit-learn estimator with fit and transform. Cleaning sits between exploring the data and building features. The goal is to make the data usable without using information from rows the model must not see.
What cleaning covers
Cleaning means fixing problems that would mislead a model or crash it. Most of them show up during exploration. Common ones are:
- Missing values, such as
NaN, empty strings, or placeholder codes like-999,"?"and"N/A". - Duplicate rows that repeat the same record.
- Wrong types, such as numbers stored as text or dates stored as strings.
- Impossible values, such as an age of 240 or a negative price.
- Inconsistent labels, such as
"NY","ny"and"New York". - Outliers, which are values far from the rest. They can be real or errors.
Some fixes involve no learned statistics, such as removing exact duplicates or converting text to numbers. You can apply those to the whole dataset. Other fixes learn a number from the data, such as a median used to fill gaps. Those must be learned from training rows only. This distinction drives the rest of the chapter.
Find the missing values first
Start by measuring. Count missing values per column and look at the share of each.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [34, 51, np.nan, 29, 42, 51],
"income": [52000, np.nan, 61000, -999, 75000, np.nan],
"city": ["Leeds", "York", None, "Leeds", "?", "York"],
"bought": [0, 1, 0, 0, 1, 1],
})
# Turn placeholder codes into real missing values.
df = df.replace({-999: np.nan, "?": np.nan})
print(df.isna().sum())
print((df.isna().mean() * 100).round(1))The replace call matters. A placeholder like -999 is not flagged by isna(), so a model would treat it as a real income and learn from it.
Why values go missing
The right treatment depends on why a value is absent. Statisticians describe three cases:
| Mechanism | Meaning | Example | Risk of simple filling |
|---|---|---|---|
| Missing completely at random (MCAR) | Absence is unrelated to any data | A sensor drops a reading at random | Low |
| Missing at random (MAR) | Absence depends on other observed columns | Younger users skip an income field | Moderate |
| Missing not at random (MNAR) | Absence depends on the missing value itself | High earners hide their income | High |
You usually cannot prove which case applies. Ask the people who collected the data, and check whether missingness correlates with other columns or with the target. If rows with missing income buy more often, the gap itself carries signal.
Options for handling missing values
There are four main choices.
- Drop rows. Simple, but you lose data and may bias the sample if the missing rows are not random. Dropping is reasonable when few rows are affected, for example under 1 to 2 percent.
- Drop columns. Reasonable when a column is mostly empty and carries little signal.
- Impute. Fill gaps with a statistic: the median for skewed numbers, the mean for roughly symmetric ones, the most frequent value for categories, or a constant such as
"missing". - Impute and flag. Fill the gap and add a column that records which values were missing. This keeps the signal when missingness is informative.
Some models, such as scikit-learn's HistGradientBoostingClassifier, accept NaN directly. Most others, including logistic regression, do not.
The median is usually safer than the mean for numeric columns, because a few extreme values pull the mean away from typical rows.
Impute without leaking
Imputation learns a statistic. If you compute the median over the full dataset and then split, test rows have influenced the value used to fill training rows. The leak is usually small, but it is still a leak, and it grows with more complex imputers. Fit the imputer on training rows and reuse it.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
df = pd.DataFrame({
"age": [34, 51, np.nan, 29, 42, 51, 38, np.nan, 45, 60],
"income": [52000, np.nan, 61000, np.nan, 75000, 58000,
49000, 66000, np.nan, 71000],
"bought": [0, 1, 0, 0, 1, 1, 0, 1, 0, 1],
})
X = df[["age", "income"]]
y = df["bought"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
imputer = SimpleImputer(strategy="median", add_indicator=True)
X_train_filled = imputer.fit_transform(X_train) # learns medians here
X_test_filled = imputer.transform(X_test) # reuses training medians
print(imputer.statistics_)
print(imputer.get_feature_names_out())
print(X_test_filled)Two details in this code are worth noting:
fit_transformis called only on training data. The test set only getstransform.add_indicator=Trueappends a 0/1 column for each feature that had missing values in the training data. Those columns are the "flag" from option 4.
In a real project, put the imputer inside a pipeline, as in the pipelines chapter. Then cross-validation refits it on each training fold automatically.
Per-column strategies
Different columns need different fills. A ColumnTransformer applies one strategy per column group.
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
df = pd.DataFrame({
"age": [34, np.nan, 29, 42],
"city": ["Leeds", "York", None, "Leeds"],
})
prep = ColumnTransformer([
("num", SimpleImputer(strategy="median"), ["age"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="missing")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
print(prep.fit_transform(df))Filling a categorical column with the constant "missing" creates its own category. That is often better than the most frequent value, because it does not pretend the person lives in the most common city.
Duplicates, types and outliers
Handle these carefully, in this order:
- Types. Convert with
pd.to_numeric(col, errors="coerce"). Values that cannot be parsed becomeNaN, which you then handle as missing. Check that dates parse withpd.to_datetime. - Duplicates.
df.drop_duplicates()removes exact copies. Be careful when the same entity legitimately appears many times, for example several orders per customer. If duplicates span the split, a model can memorize a row in training and be rewarded for it in the test set. Deduplicate before splitting, or split by group. - Outliers. Do not delete a value only because it is large. First decide whether it is an error (a height of 1700 cm) or a real extreme (a very large purchase). Fix errors by setting them to
NaN. For real extremes, consider a model that tolerates them, or a transform such as the logarithm, instead of removal. Deleting test-set outliers also makes your final score look better than production will be.
Common errors
- Filling the whole DataFrame with
df.fillna(df.mean())before splitting. This leaks statistics from test rows. - Leaving placeholder codes in place, so the model learns that
-999is an income. - Imputing the target column. Rows with a missing label usually cannot be used for supervised training. Drop them, or set them aside to predict later.
- Dropping rows with missing values in the test set. New data in production will have gaps too, and the pipeline must handle them.
- Forgetting that a column with no missing values in training may have some at prediction time.
SimpleImputerthen raises no error for a complete column, but the model getsNaNit cannot use if no imputer is present. Include an imputer on every numeric column if production data may be incomplete.
Checking the result
After cleaning, verify rather than assume. Confirm that no NaN remains in the arrays passed to a model that cannot accept them. Compare column distributions before and after imputation. If a heavily imputed column now has a spike at the median, the model sees a feature that is mostly fabricated. In that case consider the indicator column, a different model, or dropping the feature.
Exercise
You compute df["income"].median() on the full dataset, fill the gaps, then split into train and test sets. What is wrong, and how do you fix it?
Show answer
The median includes test rows, so information from the test set leaks into the training data and the test score is slightly optimistic. Split first, fit a SimpleImputer(strategy="median") on the training rows only, then call transform on both sets. Better, place the imputer in a Pipeline so cross-validation refits it on every training fold.
Exercise
A column income is missing for 30% of rows, and customers with missing income buy at twice the average rate. Which option do you choose and why?
Show answer
Impute the values and add a missing-value indicator (for example SimpleImputer(strategy="median", add_indicator=True)). Missingness itself predicts the target, so dropping the rows or filling silently would throw that signal away.