Data Preprocessing Lab
Cleaning, missing and outlying values, scaling and encoding.
- 3lessons
- 6experiments
- 5terms
Scientific introduction
Raw data is rarely fit for analysis: it has missing values, duplicates, outliers and mixed types. Preprocessing turns it into a consistent table, and every decision there influences the results.
Learning objectives
- Distinguish missingness mechanisms (MCAR, MAR, MNAR)
- Choose and justify a method for missing and outlying values
- Tell normalisation from standardisation and when to use each
- Encode categorical variables without inventing an order
- Build a repeatable pipeline and document its effect
Topics
- Missing values
- Outliers
- Scaling
- Encoding
- Pipelines
Core concepts
- MCAR
- Missingness whose probability depends on no observed or unobserved variable.
- Imputation
- Replacing missing values with estimates such as the mean, median or a model prediction.
- Outlier
- An observation far from the rest; it may be an error or a genuine rare case.
- Standardisation
- Subtracting the mean and dividing by the standard deviation to give mean 0 and standard deviation 1.
- One-hot encoding
- Representing a category as a vector that is 0 except one element equal to 1.
Theory
Missing values: mechanisms and options
Why the mechanism matters
Missingness is classed into three mechanisms: MCAR (completely random, unrelated to any variable), MAR (related to observed variables) and MNAR (related to the missing value itself). The mechanism decides whether deletion or imputation is safe.
Options
- Row deletion: simple, shrinks the sample, and biases results unless the loss is MCAR.
- Mean or median imputation: keeps the size but shrinks variance and weakens correlations.
- Multiple imputation or model-based: more accurate but more complex.
Always record the missing share per column before any decision.
Scaling, standardisation and encoding
Scaling and standardisation
Min-Max scaling maps values to [0,1] with (x-min)/(max-min) and is sensitive to outliers. Standardisation (Z-score) subtracts the mean and divides by the standard deviation, (x-μ)/σ, giving mean 0 and standard deviation 1.
Distance-based algorithms (k-means, kNN) and regularised regression need scaled features; trees do not.
Encoding
For unordered categories use one-hot encoding. Sequential integer codes (1,2,3) impose an order that does not exist.
Fit scaling statistics on training data only.
Outliers: detection and handling
Detection
The IQR rule flags values below Q1-1.5×IQR or above Q3+1.5×IQR. The Z-score rule flags values where |z| exceeds a threshold (commonly 3), but assumes a roughly normal shape and is itself affected by outliers.
Decision
Do not delete a value merely because it is extreme. Ask: is it an entry error or a genuine rare case? If genuine, deleting it loses information. Options: winsorising, a log transform, or robust statistics such as the median.
Worked examples
Deletion versus imputation
Dropping rows with missing values shrinks the sample and may bias the mean if the loss is not random. Mean imputation keeps the size but shrinks the variance. Try the experiment and compare.
Interactive experiments
Handling missing values
Learning goal: See how deletion and imputation change the mean, variance and correlation.
Explanation and scientific documentation
A share of one column is blanked by a mechanism you choose (MCAR, MAR or MNAR), then handled by one of: row deletion, mean, median, zero, or regression imputation, and results are compared with the known original.
Data: Synthetic data generated in your browser with an editable seed; the relationships are planted on purpose for learning and are not real data.
Error = (value after handling − original value). Mean imputation roughly preserves the mean when loss is random but shrinks the standard deviation.
Limits: The variable-linked mechanism here is a simplified MAR; in real work you do not know the true mechanism.
Scaling and normalisation
Learning goal: Understand how outliers affect different scaling methods.
Explanation and scientific documentation
One of these is applied to a single column: Min-Max, Z-score, robust (median/IQR), max-abs or log, optionally with injected outliers, showing the shape before and after.
Data: Synthetic data generated in your browser with an editable seed; the relationships are planted on purpose for learning and are not real data.
x′ = (x − min)/(max − min). A single outlier squeezes the remaining values into a small part of the range.
Limits: Normalisation changes the range, not the shape of the distribution.
Z-score standardisation
Learning goal: See how standardisation affects distances and k-means output.
Explanation and scientific documentation
Points with two differently-scaled features are clustered before and after standardising, so you can see the large-unit feature dominate.
Data: Synthetic data generated in your browser with an editable seed; the relationships are planted on purpose for learning and are not real data.
z = (x − μ)/σ. k-means relies on Euclidean distance and so is sensitive to scale.
Limits: The number of clusters k is set by hand and may not match the true structure.
Outlier detection
Learning goal: Compare detection rules (IQR, Z-score, modified Z and k-NN distance) and their sensitivity to injected values.
Explanation and scientific documentation
Known outliers are injected into synthetic data, then the chosen rule is scored on how many it catches and how many normal points it wrongly flags.
Data: Synthetic data generated in your browser with an editable seed; the relationships are planted on purpose for learning and are not real data.
IQR: outside [Q1 − k·IQR, Q3 + k·IQR]. Z: |z| > threshold. The latter is affected by the outliers themselves through the mean and standard deviation.
Limits: "Statistically extreme" does not mean "wrong"; the decision needs domain knowledge.
Encoding categorical variables
Learning goal: Compare one-hot, label, frequency and target encoding.
Explanation and scientific documentation
A column's categories are encoded with the chosen method, showing the resulting columns and the encoding's relation to the numeric target.
Data: Synthetic data generated in your browser with an editable seed; the relationships are planted on purpose for learning and are not real data.
Target-mean encoding uses the target mean per category; computed on all data it leaks.
Limits: The experiment computes the encoding on all data for illustration; in real work it must be computed inside cross-validation.
A cleaning pipeline
Learning goal: See the effect of each cleaning step on rows and missing values.
Explanation and scientific documentation
You enable steps (trim text, drop duplicates, impute, clip) and the data state after each is shown.
Data: Synthetic data generated in your browser with an editable seed; the relationships are planted on purpose for learning and are not real data.
Order matters: deduplicating before imputing changes the statistics used for imputation.
Limits: Synthetic data with deliberately planted faults; real-world faults are more varied.
Related algorithms and methods
Z-score
Measures distance from the mean in standard deviations.
IQR rule
Flags a value outside Q1-1.5·IQR or Q3+1.5·IQR.
Min-Max scaling
Maps values linearly to [0,1].
Suitable datasets
- Customers (synthetic) Synthetic, generated in the browser
- Students (synthetic) Synthetic, generated in the browser
Practical projects
- Data cleaning challenge Beginner
Assessment questions
Sources and references
- Little, R. J. A., & Rubin, D. B. (2019). Statistical Analysis with Missing Data (3rd ed.). Wiley DOI (bibliographic data entered by the editor, not machine-checked)
- Wickham, H. (2014). Tidy data. Journal of Statistical Software, 59(10) DOI (bibliographic data entered by the editor, not machine-checked)
- Pedregosa, F., et al. (2011). Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12, 2825-2830 Link (bibliographic data entered by the editor, not machine-checked)
- Tukey, J. W. (1977). Exploratory Data Analysis. Addison-Wesley (bibliographic data entered by the editor, not machine-checked)
