Data Cleaning and Missing Values
Handling missing values, outliers, duplicates, inconsistent categories and type errors in a principled, reproducible way.
Beginner · about 6 hours · difficulty 2/5
Learn first: Exploratory Data Analysis
Real data is messy. Cleaning decisions change model behaviour, so make them deliberately and encode them in code rather than editing files by hand.
Missing values
- Understand the mechanism: missing completely at random, at random, or not at random (a blank income field may mean something).
- Simple imputation: median for numeric, most frequent or an explicit
missingcategory for categorical. - Add missing indicator columns when missingness may be informative.
- Model-based imputation (KNN, iterative) is optional and rarely worth the complexity early on.
- Tree boosting libraries handle
NaNnatively, which is often the simplest option.
Other cleaning
- Outliers: distinguish errors (fix or drop) from real extremes (keep, maybe clip or log-transform).
- Duplicates: exact and near duplicates can leak between train and test.
- Inconsistent categories:
NY,New York,new yorkshould be one value. - Types: numbers stored as strings, dates as text, units mixed in one column.
Critical rule
Fit imputers and other data-dependent cleaning on training data only, then apply to validation and test. scikit-learn pipelines (later) make this automatic.
Good enough to move on when your cleaning is a rerunnable function or pipeline, not a sequence of manual notebook edits.
Key concepts
- Missing data mechanisms
- Simple imputation
- Missing indicators
- Outlier handling
- Deduplication
- Category normalization
- KNN and iterative imputation
Mini project
Write a reusable clean() function for the Kaggle House Prices data that handles every missing column with a justified strategy, fixes types, and is covered by a few assert-based sanity checks.
Check yourself
Why is it wrong to compute the median for imputation on the full dataset before splitting into train and test?
Free resources
- Kaggle Learn: Data Cleaning (Kaggle)
- scikit-learn: Imputation of missing values (scikit-learn)