The most sophisticated machine learning model in the world will produce disastrous predictions if trained on garbage data (Garbage In, Garbage Out). In this class, we build systematic, production-ready data cleaning pipelines covering missing data mechanisms, advanced imputation, and outlier treatments.
Figure 23.1: Systematic Data Cleaning — Profiling, Missing Imputation, Outlier Capping & Hygiene.
| Technique | When to Use | Risks / Trade-offs |
|---|---|---|
| Listwise Deletion (Drop Rows) | Less than 2% of records missing purely at random (MCAR). | Drastically reduces training sample size if many columns have scattered missing values. |
| Median Imputation | Numeric features with moderate skewness. | Underestimates standard deviation; fails to capture multi-feature correlations. |
| KNN / Iterative Imputer (MICE) | Features strongly correlated with other attributes. | Computationally expensive; must be fitted strictly on training data to prevent leakage. |
| Missingness Indicator Flag | MNAR features where the act of missingness carries predictive signal. | Adds an extra binary column (col_is_missing) for tree models to exploit. |
import numpy as np
import pandas as pd
from sklearn.impute import KNNImputer
# Sample dirty dataset with missing values and severe outliers
df = pd.DataFrame({
'age': [25, np.nan, 32, 45, 150, 29, 34, 40], # 150 is a corrupt outlier
'salary': [50000, 62000, np.nan, 95000, 78000, 54000, 68000, 1200000], # 1.2M is outlier
'rating': [4.2, 3.8, 4.5, np.nan, 4.0, 3.9, 4.8, 5.0]
})
# Step 1: Cap extreme salary outliers via Winsorization (95th percentile upper fence)
upper_cap = df['salary'].quantile(0.95)
df['salary_capped'] = np.where(df['salary'] > upper_cap, upper_cap, df['salary'])
# Step 2: Fix unrealistic age values (> 100 set to NaN)
df.loc[df['age'] > 100, 'age'] = np.nan
# Step 3: Add missingness indicator
df['age_was_missing'] = df['age'].isnull().astype(int)
# Step 4: Multivariate KNN Imputation (k=2 neighbors)
imputer = KNNImputer(n_neighbors=2)
clean_features = imputer.fit_transform(df[['age', 'salary_capped', 'rating']])
df_cleaned = pd.DataFrame(clean_features, columns=['age', 'salary', 'rating'])
print(df_cleaned.round(1))
Why is an outlier not always an error? Give an example where removing outliers ruins model utility. (Answer: In fraud detection and network intrusion detection, the outliers ARE the target events! Removing them destroys the training signal).
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
The statistical foundation of the IQR 1.5 fence and 3-sigma outlier rules.
Transform cleaned features into numeric matrices for machine learning.
Identify data quality issues through visual distributions before cleaning.
Clean dirty real-world datasets with missing values and severe outliers.