Data Cleaning: Missing Data Imputation, Outlier Detection & Data Hygiene

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.

Data Cleaning and Outlier Pipeline

Figure 23.1: Systematic Data Cleaning — Profiling, Missing Imputation, Outlier Capping & Hygiene.

1. Missing Data Treatment Strategies

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.

2. Outlier Detection: IQR vs. Z-Score vs. Isolation Forest

The IQR Fence Method (Robust Non-Parametric)

\[ \text{Lower Fence} = Q_1 - 1.5 \times \text{IQR}, \quad \text{Upper Fence} = Q_3 + 1.5 \times \text{IQR} \]

The Z-Score Method (Parametric Gaussian)

\[ Z = \frac{x - \mu}{\sigma} \implies \text{Flag as Outlier if } |Z| > 3.0 \]

Production Python Pipeline: Cleaning & Winsorization

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))

University Viva & Exam Checklist

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).

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What are the three mechanisms of missing data?

1. MCAR (Missing Completely at Random): Missingness has no relationship with observed or unobserved data. 2. MAR (Missing at Random): Missingness depends systematically on other observed variables, but not the missing value itself. 3. MNAR (Missing Not at Random): Missingness depends directly on the unobserved missing value itself (e.g., high earners refusing to disclose income).

Q2. Why should you avoid simple mean imputation for skewed data?

Mean imputation artificially compresses variance, distorts distribution shapes, attenuates correlations between features, and produces severe bias on skewed distributions. Median imputation or multivariate iterative methods (MICE / KNN) are far more reliable.

Q3. What is John Tukey's 1.5*IQR outlier rule?

Calculate the 25th percentile (Q1) and 75th percentile (Q3). The Interquartile Range is IQR = Q3 - Q1. Any value falling below the Lower Fence (Q1 - 1.5*IQR) or above the Upper Fence (Q3 + 1.5*IQR) is classified as an empirical outlier.

Q4. What is Winsorization (outlier capping)?

Rather than dropping valuable outlier rows (which reduces training sample size), Winsorization caps extreme values at a predetermined percentile threshold (such as replacing all values above the 99th percentile with the 99th percentile value).

Q5. How does KNNImputer work in Scikit-Learn?

KNNImputer identifies the k-nearest data records to a row missing a value (based on Euclidean distance across non-missing features) and imputes the weighted average of those neighbors' values.

Explore Related Data Science Tutorials & Next Steps

Broaden your statistical analysis, Python data wrangling, and production engineering expertise:

Descriptive Statistics: Spread & IQR

The statistical foundation of the IQR 1.5 fence and 3-sigma outlier rules.

Feature Engineering: Scalers & Encoders

Transform cleaned features into numeric matrices for machine learning.

Exploratory Data Analysis Framework

Identify data quality issues through visual distributions before cleaning.

12+ Hands-on Practice Labs & Datasets

Clean dirty real-world datasets with missing values and severe outliers.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!