Data Cleaning: Handling Missing Values, Duplicates & Outliers
MCAR vs. MAR vs. MNAR missingness, Mean/Median/KNN imputation, Missingness Indicator flags, and IQR vs. Z-Score outlier treatment
Data Cleaning prepares raw tables for ML by fixing missing values (NaNs), removing duplicate records, and detecting or capping extreme outliers before training.
Most algorithms (Linear Regression, SVM, KNN, Neural Nets) crash on NaN values, and a single corrupted outlier (like age = 999) can tilt an entire regression line.
Real-world production databases are 10%–40% missing or messy — clean imputation is the difference between a working model and a ValueError: Input contains NaN crash.
Production pipelines must handle unseen NaN values at inference time without crashing, even if a column had zero missing values during training.
Understanding why a value is missing (e.g., blank credit_history means a new borrower) often yields the strongest predictive feature in the entire table.
Classic interview question: 'When should you impute with the median instead of the mean, and when should you add a missingness flag?'
A house-price column is heavily right-skewed with a few $50M mansions. Which single-value imputer is safest for missing prices?
- Choose between dropping rows, Mean/Median/Mode imputation, and KNN/Iterative imputation.
- Explain why adding a binary
was_missingindicator column often boosts model accuracy when data is Missing Not At Random (MNAR). - Detect outliers using both the IQR rule () and Z-Score (), and choose between dropping vs. Winsorizing (clipping).
- Fit every imputer strictly on the training split to prevent data leakage.
Missing values and outliers are signals, not just annoyances. Before blindly deleting rows or filling zeros, ask two questions: (1) Is the missingness itself informative? (add a col_is_missing flag!), and (2) Is an outlier a sensor bug (age = -5) or a real high-value event (a VIP whale customer)?
1. Missing Value Strategies: Drop vs. Impute vs. Flag
Suppose a medical form has a blank field for blood_sugar. Maybe the nurse forgot to type it (random), or maybe the doctor skipped the test because the patient looked completely healthy (informative!).
Practical Imputation Playbook
- Numerical (symmetric): Mean imputation.
- Numerical (skewed / has outliers): Median imputation (safe default!).
- Categorical: Mode (most frequent) OR a dedicated
"Missing"category (often best!). - Missingness Indicator (
col_was_missing = 0/1): Always test adding a binary flag whenever of a column is missing — if missingness is MNAR (Missing Not At Random), the flag carries huge predictive signal! - Leakage Rule: Compute the median/mode ONLY on the training set, then apply that exact number to validation and test sets.
2. Outlier Detection: IQR Fences vs. Z-Score & Winsorization
One typo turning $50.00 into $50,000 can ruin an entire Linear Regression slope. Yet blindly deleting valid high-spend customers can blind your model to VIPs.
Two Standard Detection Rules
- IQR Rule (Best for Skewed Data): Flag values below or above .
- Z-Score Rule (Best for Bell-Shaped Data): Flag values with .
Three Ways to Treat Outliers
- Drop if it is clearly a data-entry/sensor bug (
age = 999,weight = -10). - Winsorize (Clip) to the 1st and 99th percentiles so extreme valid values don't explode gradients.
- Keep + Use Robust Models: Tree models (Random Forest, XGBoost) and Huber Loss naturally ignore extreme input outliers.
Raw salaries ($k): [40, 60, 80, 100, 1000]. Look at what happens to the 4 normal employees [40, 60, 80, 100]:
CRUSHED into [0.00, 0.06]!
All 4 normal people look negative!
100% UNCHANGED by the outlier!
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Almost never! Filling missing age or temperature with 0 tells the model the person is a newborn or it is freezing outside, distorting means and slopes.
Unscaled Ravine (Zig-Zag!) vs. StandardScaler Circle (Straight Shot!)
Watch both gradient-descent marbles race simultaneously with the exact same learning rate!
import numpy as np
# Leakage-Free Median Imputation + Missingness Flag + IQR Clipping
train = np.array([22.0, 25.0, np.nan, 28.0, 30.0, 29.0, 250.0]) # 250 is an outlier
test = np.array([24.0, np.nan, 310.0])
# 1. Fit statistics STRICTLY on training data
train_valid = train[~np.isnan(train)]
med = float(np.median(train_valid))
q1, q3 = np.percentile(train_valid, [25, 75])
iqr = q3 - q1
lo, hi = q1 - 1.5 * iqr, q3 + 1.5 * iqr
def clean_feature(arr: np.ndarray):
was_missing = np.isnan(arr).astype(float)
filled = np.where(np.isnan(arr), med, arr)
clipped = np.clip(filled, lo, hi)
return np.column_stack([clipped, was_missing])
print(f"Train median={med:.1f}, IQR bounds=[{lo:.1f}, {hi:.1f}]")
print("Cleaned test [value, was_missing]:\n", clean_feature(test))
train_test_split..fit() the imputer on X_train and .transform() X_val and X_test.col_was_missing indicator column often helpful alongside median imputation?