Intermediate
11 min read
#Data Cleaning#Imputation#Outliers#EDA
Data Cleaning & Preprocessing Best Practices
Comprehensive guide on Data Cleaning & Preprocessing Best Practices.
Data Cleaning & Preprocessing Best Practices
1. Overview#
Real-world data is noisy, incomplete, and inconsistent. High-performing machine learning models require rigorous preprocessing: handling missingness (MCAR, MAR, MNAR), outlier mitigation, and variance stabilization.
Never fit data imputers or scalers on the entire dataset. Always fit on the training split and transform the validation/test splits to prevent Data Leakage.
2. Missing Value Imputation Strategies#
| Missing Pattern | Best Imputation Technique | When to Use |
|---|---|---|
| Numerical (Symmetric) | Mean Imputation | Normally distributed numerical features without heavy tails |
| Numerical (Skewed) | Median Imputation | Features with extreme outliers |
| Categorical | Mode / Dedicated Unknown Category | High cardinality categorical variables |
| Multivariate Relationships | IterativeImputer (MICE) / KNNImputer | Complex tabular interactions across multiple correlated columns |
3. Outlier Detection with Interquartile Range (IQR) & Z-Score#
🐍 PythonInteractive WebAssemblyimport pandas as pd
import numpy as np
def cap_outliers_iqr(df: pd.DataFrame, column: str, multiplier: float = 1.5) -> pd.Series:
"""Winsorizes numerical values outside the IQR bounds."""
Q1 = df[column].quantile(0.25)
Q3 = df[column].quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - multiplier * IQR
upper_bound = Q3 + multiplier * IQR
return df[column].clip(lower=lower_bound, upper=upper_bound)
4. Best Practices Checklist#
- Inspect missingness patterns with
df.isnull().sum()and missingno matrix visualizations. - Standardize string columns (strip whitespace, lowercase, normalize unicode accents).
- Validate column data types before persisting to Parquet or feeding into ML pipelines.
Knowledge Checkpoint
Data Cleaning & Preprocessing Checkpoint
Q1.What statistical measure of central tendency is most robust to extreme outliers when imputing missing values in skewed numerical data?
AMean
BMedian
CStandard Deviation
DVariance
Q2.In the Interquartile Range (IQR) method, what boundaries typically define an outlier?
AValues below $Q1 - 1.5 \times IQR$ or above $Q3 + 1.5 \times IQR$
BValues within 1 standard deviation of the mean
CValues exactly equal to the median
DValues strictly greater than 100
Q3.Why must imputation and scaling statistics (e.g. mean, variance) be fit ONLY on the training split and not on the whole dataset?
ATo prevent data leakage from the test set into the model training pipeline.
BBecause scikit-learn throws an error if fit on test data.
CTo reduce training time by 90%.
DBecause test datasets cannot contain null values.
Track Your Learning
Finished studying this notebook?
Mark this guide as completed to update your course progress roadmap.