Level 3 In-Depth AI · Classical Machine Learning
Data Cleaning and Preparation
Turning messy real-world tables into clean numbers a model can learn from. Fixing errors, filling gaps, taming outliers, putting features on comparable scales, encoding categories as numbers and handling rare classes, all without leaking the test set into training.
- Level
- ●●●●● Beginner
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 2 concepts →
- Quiz
- 5 questions ↓
Read first
Pandas and Working with DataThe full path from zero — 2 concepts before this one
- Python for AI
- Pandas and Working with Data
- Data Cleaning and Preparation
Read them roughly in this order. See it on the concept map →
Why it matters
Machine learning courses start with clean datasets: every value present, every column a number, every label correct. Real data is nothing like that. Customer records have blank fields and impossible ages. Sensor logs contain spikes where a cable came loose. The same city is spelled three ways. Prices are stored as text with currency signs. One class of interest is 0.1% of the rows.
A model can't fix any of this for you. Most algorithms can't even run on a missing value or a word, and the ones that can will happily learn from a typo as if it were truth. "Garbage in, garbage out" is the oldest rule in computing. The often-quoted claim that data scientists spend 80% of their time preparing data comes from informal industry surveys and is folklore rather than a measurement, but few practitioners dispute its spirit. On tabular problems, careful cleaning and preparation usually improve results more than switching algorithms.
This chapter covers the core steps: inspecting, cleaning, handling missing values and outliers, scaling, encoding categories and dealing with imbalanced classes. It also covers the rule that ties them together: every preparation step is part of the model and must be learned from training data only.
The intuition
Think of preparing ingredients before cooking. You wash the vegetables, throw out the mouldy ones, cut everything to similar sizes so it cooks evenly, and measure in consistent units. You don't taste the dish your guests will eat to decide how much salt to put in the practice batch.
Each step has a counterpart:
- Washing and discarding: fixing typos, removing duplicates, correcting impossible values. This is data cleaning.
- Filling gaps: deciding what to do with missing values.
- Cutting to similar sizes: putting numeric features on comparable scales, so that no feature dominates just because of its units.
- Consistent units: turning categories like "Leeds" or "York" into numbers a model can use.
- Not tasting the guests' dish: computing all of these choices from the training data and applying them unchanged to the test data.
Key idea Clean the data, fill gaps, scale numbers and encode categories, and do every step that learns something (a mean, a median, a list of categories) on the training data only, inside a pipeline. Then the same steps apply identically to new data.
How it works
Step 0: look at the data
Before changing anything, look. With Pandas and Working with Data: df.info() for column types and non-missing counts, df.describe() for ranges, df.isna().sum() for gaps, df["col"].value_counts() for categories, and plots of each feature (Visualising Data). You are hunting for:
- numbers stored as text (
"£1,200"), and dates stored as strings; - impossible values: negative ages, a 9,500 m² flat, a date in 2099;
- placeholder codes that mean "missing":
-1,999,"N/A","?"; - inconsistent spellings:
"York","york","York "; - duplicated rows;
- labels that look wrong when you read a sample by hand.
Missing values
A missing value is an empty cell, usually shown as NaN ("not a number") or None. Before filling it, ask why it is missing:
- Missing completely at random: a sensor dropped a reading at random. Filling the gap with a typical value is reasonable.
- Missing for a reason connected to other features: older patients skip a particular test more often. Other columns can help predict the gap.
- Missing for a reason connected to the value itself: people with very high incomes leave the income field blank. Here the fact that it is missing is information.
The options:
- Drop rows with gaps. Simple, but wasteful, and your model will be unable to predict for any future row with a gap.
- Drop the column, if it is mostly empty and not important.
- Impute, which means filling the gap with an estimate. Imputation with the median (for numbers) or the most frequent value (for categories) is the usual baseline. Smarter imputers predict the missing value from the other columns (scikit-learn's
KNNImputerandIterativeImputer). - Add a "was missing" indicator column alongside the imputed value, so the model can learn if missingness itself matters. This is cheap and often helps.
- Some models handle gaps natively: gradient-boosted trees such as LightGBM and XGBoost learn which way to send missing values at each split.
Outliers
An outlier is a value far from the rest. It might be an error (a typo, a unit mix-up, a sensor fault) or a genuine rare case (a billionaire's income, a once-a-decade storm). Treat them differently:
- Errors: fix them if you can (9500 m² was probably 95), otherwise mark them as missing.
- Genuine extremes: keep them, but consider whether they will distort the model. Options are clipping (capping values at, say, the 1st and 99th percentiles), a log transform for long-tailed quantities like income or prices, a robust loss (Loss Functions), or a model that is naturally insensitive to them, such as tree-based models.
Never delete outliers just because they are inconvenient. In fraud detection or fault monitoring, the outliers are the point (Anomaly Detection).
Scaling numeric features
Features come in wildly different units: age in years (0 to 100), income in pounds (0 to millions), a ratio (0 to 1). Many algorithms are sensitive to this. Gradient descent converges slowly on badly scaled features. Distance-based methods such as k-Nearest Neighbours and k-Means Clustering let the biggest-numbered feature dominate the distance. Regularised models penalise weights unevenly. Feature scaling puts them on comparable scales. Tree-based models are the main exception: they split on thresholds, so scaling doesn't affect them.
Three common scalers, worked by hand on the values 50, 60, 70, 80, 90:
- Standardisation (z-scores): subtract the mean, divide by the standard deviation. The mean is 70 and the standard deviation is . So the values become . After standardising, each feature has mean 0 and standard deviation 1. This is the default choice.
Here ("mu") is the mean and ("sigma") the standard deviation, both computed on the training data.
- Min–max scaling: subtract the minimum, divide by the range. The values become . Useful when an algorithm expects inputs in , such as image pixels.
- Robust scaling: subtract the median, divide by the interquartile range (the spread of the middle half of the data). Here the median is 70 and the interquartile range is , giving .
They agree on clean data. They disagree when there is an outlier. Add a sixth value, 400:
Encoding categories
Models need numbers, so text categories must be converted.
- One-hot encoding creates one new 0/1 column per category. A
citycolumn with values Leeds, York and Hull becomes three columns,city_Leeds,city_York,city_Hull, and each row has a 1 in exactly one of them. This makes no false claim that one city is "bigger" than another. It is the default for categories with up to a few dozen values. - Ordinal encoding maps categories to integers: small = 0, medium = 1, large = 2. Use it only when the order is real. For unordered categories it invents a fake ordering that linear models will take literally. Tree models tolerate it better.
- High-cardinality categories (postcodes, product IDs, thousands of values) make one-hot encoding unwieldy. Options include grouping rare values into "other", target encoding and learned embeddings; see Feature Engineering.
Always decide what happens to a category that appears at prediction time but never in training (a new city). Scikit-learn's OneHotEncoder(handle_unknown="ignore") encodes it as all zeros instead of crashing.
Imbalanced classes
When one class is rare (fraud, disease, defects), a model trained naively may ignore it, because predicting the majority class already gives a low loss and high accuracy (Evaluation Metrics). Remedies:
- Class weights: make each mistake on the rare class count more in the loss.
class_weight="balanced"in scikit-learn weights each class inversely to its frequency. Usually the first thing to try. - Oversampling: duplicate rare-class examples in the training set, or create synthetic ones by interpolating between neighbours (SMOTE).
- Undersampling: throw away some majority-class examples. Faster training, but it wastes data.
- Moving the decision threshold after training, which is often all you need (Evaluation Metrics).
Resample only the training data, never the validation or test data, or your evaluation no longer reflects reality. Remember too that rebalancing distorts the predicted probabilities, which then need recalibrating if you use them as probabilities.
The golden rule: prepare inside the pipeline
Every step above that learns a number from the data (the median for imputation, the mean and standard deviation for scaling, the list of categories for encoding) must learn it from the training rows only. Learn it from all rows and test-set information leaks into training, inflating your scores (Training, Validation and Test Sets). The clean way is a preprocessing pipeline: chain the steps and the model into one object, so that fit learns everything from the training data and predict applies the same learned numbers to any new data.
The pipeline also solves a deployment problem: the exact same transformations run in production, with no chance of someone re-implementing the scaling slightly differently.
In code
A small messy table, cleaned step by step with pandas. (On a real project you would fit these fill values on the training split only; the next example shows how.)
import numpy as np
import pandas as pd
df = pd.DataFrame({
"area_m2": [54, 88, np.nan, 120, 61, 75, 9500], # 9500: a typo for 95?
"bedrooms": [1, 3, 2, 4, np.nan, 2, 3],
"city": ["Leeds", "york", "Leeds", "York", "Hull", None, "Leeds"],
"price_k": [210, 265, 190, 310, 150, 205, 280],
})
print(df.isna().sum().to_dict()) # missing values per column
df["city"] = df["city"].str.title() # "york" and "York" are the same city
df.loc[df["area_m2"] > 1000, "area_m2"] = np.nan # impossible value -> treat as missing
df["area_missing"] = df["area_m2"].isna() # keep the fact that it was missing
df["area_m2"] = df["area_m2"].fillna(df["area_m2"].median())
df["bedrooms"] = df["bedrooms"].fillna(df["bedrooms"].median())
df["city"] = df["city"].fillna("Unknown")
df = pd.get_dummies(df, columns=["city"], dtype=int) # one-hot encode
print(df.to_string())
# {'area_m2': 1, 'bedrooms': 1, 'city': 1, 'price_k': 0}
# area_m2 bedrooms price_k area_missing city_Hull city_Leeds city_Unknown city_York
# 0 54.0 1.0 210 False 0 1 0 0
# 1 88.0 3.0 265 False 0 0 0 1
# 2 75.0 2.0 190 True 0 1 0 0
# 3 120.0 4.0 310 False 0 0 0 1
# 4 61.0 2.5 150 False 1 0 0 0
# 5 75.0 2.0 205 False 0 0 1 0
# 6 75.0 3.0 280 True 0 1 0 0
Note that isna() found only one missing area at first. The 9,500 m² typo was not "missing" until we decided it was impossible. Lower-case "york" would have become a separate city if we hadn't normalised the spelling.
The same ideas as a scikit-learn pipeline, on the diabetes data with 15% of three columns knocked out and the sex column turned into text:
import numpy as np
import pandas as pd
from sklearn.datasets import load_diabetes
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
# The diabetes data, made realistically messy
df = load_diabetes(as_frame=True, scaled=False).frame
rng = np.random.default_rng(0)
df["sex"] = df["sex"].map({1.0: "F", 2.0: "M"}) # a text category
for col in ["bmi", "bp", "s5"]:
df.loc[rng.random(len(df)) < 0.15, col] = np.nan # 15% missing in each
X, y = df.drop(columns="target"), df["target"]
print("rows with any gap:", X.isna().any(axis=1).sum(), "of", len(X))
numeric = [c for c in X.columns if c != "sex"]
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median", add_indicator=True),
StandardScaler()), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), ["sex"]),
])
model = make_pipeline(prep, Ridge(alpha=1.0))
print("impute, all rows: R^2 = %.3f" % cross_val_score(model, X, y, cv=5).mean())
complete = X.notna().all(axis=1) # the lazy alternative
print("drop incomplete rows: R^2 = %.3f on %d rows"
% (cross_val_score(model, X[complete], y[complete], cv=5).mean(), complete.sum()))
# rows with any gap: 167 of 442
# impute, all rows: R^2 = 0.431
# drop incomplete rows: R^2 = 0.432 on 275 rows
Gaps in just three columns touch 38% of the rows. Dropping them scores about the same, but on a smaller, different set of patients, and the resulting model could not predict for anyone with a missing measurement. The pipeline version keeps every row, and because it lives inside cross_val_score, its medians and scaling are re-learned on each training fold.
Finally, class weights on an imbalanced problem: the breast-cancer data with most malignant cases removed, leaving 4.5% positives:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score, precision_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
y = 1 - y # 1 = malignant
rng = np.random.default_rng(0)
keep = (y == 0) | (rng.random(len(y)) < 0.08) # keep only ~8% of malignant cases
X, y = X[keep], y[keep]
print(f"{y.sum()} malignant of {len(y)} ({y.mean():.1%})")
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.4, stratify=y, random_state=0)
for cw in [None, "balanced"]:
m = make_pipeline(StandardScaler(), LogisticRegression(C=0.05, class_weight=cw))
pred = m.fit(X_tr, y_tr).predict(X_te)
print(f"class_weight={cw!s:9} recall {recall_score(y_te, pred):.2f} "
f"precision {precision_score(y_te, pred):.2f}")
# 17 malignant of 374 (4.5%)
# class_weight=None recall 0.29 precision 1.00
# class_weight=balanced recall 0.86 precision 1.00
Unweighted, the model catches only 2 of the 7 malignant tumours in the test set. Weighted, it catches 6, with no extra false alarms here. (With only 7 positives these numbers are rough; Cross-Validation would give a steadier picture.)
Common pitfalls
- Fitting preprocessing on all the data. Scaling, imputing or encoding before the split leaks test information. Use a pipeline.
- Silent placeholders.
-1,0or999meaning "unknown" look like real numbers to a model. Convert them toNaNfirst. - Dropping rows with gaps by reflex. It shrinks the data, can bias it (if gaps aren't random) and leaves you unable to predict for incomplete rows later.
- Ordinal-encoding unordered categories for a linear model, which then believes "York" is twice "Leeds".
- Resampling before splitting. Oversampled copies of the same example end up on both sides of the split, and validation scores soar.
- Inconsistent preparation between training and serving. Re-implementing preprocessing by hand in production is a classic source of silent bugs. Ship the fitted pipeline itself.
Watch out Look at the raw rows, not just summary statistics. Many disasters (labels shifted by one row, a column of all zeros, two datasets joined on the wrong key, test rows duplicated in training) are obvious in a minute of reading and invisible in a table of means.
Where it leads
- Feature Engineering: once the data is clean, creating new, more informative features.
- Training, Validation and Test Sets and Cross-Validation: preparation must respect the split.
- Evaluation Metrics: how to judge models on imbalanced data.
- Data Pipelines and Datasets: preparation at production scale, with validation and versioning.
- Images as Data and Tokenization: the preparation steps for images and text.
- Bias and Fairness: cleaning choices (whom to drop, how to fill gaps) can affect groups differently.
A bit of history
Data cleaning is as old as statistics, but it was long treated as unglamorous groundwork. John Tukey's Exploratory Data Analysis (1977) made looking at data before modelling a discipline of its own and gave us the box plot, whose whiskers are still a common rule for flagging outliers. Donald Rubin set out the modern theory of missing data in 1976, including the distinction between data missing at random and not at random, and with Roderick Little wrote the standard textbook on it. Nitesh Chawla and colleagues introduced SMOTE for imbalanced data in 2002. Scikit-learn's Pipeline and later ColumnTransformer (2018) made leak-free preparation the default way to work in Python. More recently, the "data-centric AI" movement, promoted by Andrew Ng among others around 2021, argued that improving data is often a better investment than improving models.
Try it
- Standardise the values 2, 4, 4, 4, 5, 5, 7, 9 by hand. (Their mean is 5 and their standard deviation is 2.)
- In the diabetes pipeline, change the imputer to
strategy="mean"and removeadd_indicator=True. Does the score change? Then raise the missing fraction from 15% to 40%.- In the imbalance example, keep
class_weight=Nonebut predict malignant when the probability is at least 0.1 instead of 0.5 (usepredict_proba). How does recall compare with class weighting?Hint for 1: the z-scores are : −1.5, −0.5, −0.5, −0.5, 0, 0, 1, 2.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Kaggle Learn
Bite-sized interactive courses (Python, Pandas, intro ML, feature engineering) that run in the browser.
scikit-learn: Preprocessing data
The guide to scalers, encoders, discretisers and other transformers, with advice on which to use when and how they behave with outliers.
scikit-learn: Common Pitfalls and Recommended Practices
Short, concrete examples of data leakage, inconsistent preprocessing and randomness mistakes, and how pipelines prevent them.
10 Minutes to pandas
The official quick tour of DataFrames.
imbalanced-learn
A scikit-learn-compatible library of over- and under-sampling methods (SMOTE and many variants) with a user guide on learning from imbalanced classes.
Designing Machine Learning Systems
The practical guide to data, features, deployment, monitoring and iteration in production ML.
SMOTE: Synthetic Minority Over-sampling Technique
The paper that introduced creating synthetic rare-class examples by interpolating between neighbours, still the best-known resampling method.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/data-preparation.md