Sub topic 4
Cleaning data and handling missing values
This chapter assumes you know basic pandas (selecting columns, isna, groupby) and have seen a train/test split. It covers what to check in a raw table and how to fill gaps without leaking information from the test rows.
What cleaning covers
Cleaning turns the raw table from exploration into one a model can use. The common jobs are:
- Fixing types, such as numbers stored as text or dates stored as strings.
- Removing exact duplicate rows.
- Replacing impossible or sentinel values (for example
-999or an age of 250) with a missing marker. - Deciding what to do with missing values.
Only the last job needs care about the split. Counting and fixing types are safe on the full table, because they use no statistics from the data. Anything that learns a number from the data, such as a median, must be learned on training rows only.
Why values are missing
The reason matters more than the count.
| Pattern | Meaning | Example |
|---|---|---|
| Missing completely at random | Gaps unrelated to any value | A sensor dropped a reading |
| Missing at random | Gaps depend on other columns | Younger users skip the income field |
| Missing not at random | Gaps depend on the missing value itself | High earners hide their income |
Simple filling works best for the first pattern. In the other two, the fact that a value is missing is itself a signal.
Your options
- Drop rows. Fine when few rows are affected and the gaps look random. It shrinks the data and can bias it.
- Drop a column. Reasonable when most of it is empty.
- Impute. Fill with the median or mean for numbers, and the most frequent value for categories. The median resists outliers.
- Add a missing indicator. A new 0/1 column that records which values were filled. It keeps the "was missing" signal.
Imputing without leakage
The median is a statistic. If you compute it on the whole table, the test rows influence the training data. Fit the imputer on training rows and reuse it on the test rows.
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": [25, 32, np.nan, 41, 29, np.nan, 52, 38],
"income": [40, 52, 48, np.nan, 45, 60, np.nan, 58],
})
df = df.drop_duplicates()
print(df.isna().sum())
train, test = train_test_split(df, test_size=0.25, random_state=0)
imputer = SimpleImputer(strategy="median", add_indicator=True)
train_filled = imputer.fit_transform(train) # learns medians from train only
test_filled = imputer.transform(test) # reuses those medians
print(imputer.statistics_)
print(test_filled)fit_transform learns the medians from train. transform applies the same medians to test. With add_indicator=True, the output gains extra columns that flag which features had gaps in the training data.
Common mistakes
- Filling a categorical column with a mean or a number that looks like a real category.
- Dropping rows with missing values from the test set. At prediction time, new rows will have gaps too, so the model must handle them.
- Ignoring sentinel values. A
-999left in place will be treated as a real number.
Exercise
A column has 40% missing values, and the gaps occur mostly for customers who cancelled. Should you simply drop those rows or fill with the median? Explain.
Show answer
Neither is safe on its own. Because the gaps are linked to the outcome, dropping rows would remove many cancelled customers and bias the data. A median fill hides the pattern. Impute the median (fitted on training rows only) and add a missing indicator column, so the model can use the fact that the value was missing.