Real data is rarely ready for a model. Numbers sit on very different scales, some values are missing, and important information such as a city name is stored as text. Preprocessing turns this raw table into clean numeric input. Doing it inside a scikit-learn pipeline keeps the steps in order, applies them identically to new data and prevents data leakage.
In this lesson you will learn
- Standardisation and min-max scaling
- Which models need scaling
- Filling missing values with
SimpleImputer - Turning categories into numbers with one-hot encoding
- Combining everything with
ColumnTransformerandPipeline
Scaling Numeric Features
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
df = pd.DataFrame({"age": [22, 35, 47, 58], "salary": [18000, 42000, 65000, 90000]})
standard = StandardScaler().fit_transform(df)
minmax = MinMaxScaler().fit_transform(df)
print("Standardised (mean 0, std 1):")
print(pd.DataFrame(standard, columns=df.columns).round(2))
print("\nMin-max scaled (0 to 1):")
print(pd.DataFrame(minmax, columns=df.columns).round(2))
Output
Standardised (mean 0, std 1):
age salary
0 -1.38 -1.34
1 -0.41 -0.44
2 0.48 0.42
3 1.30 1.36
Min-max scaled (0 to 1):
age salary
0 0.00 0.00
1 0.36 0.33
2 0.69 0.65
3 1.00 1.00
- Standardisation (
StandardScaler) subtracts the mean and divides by the standard deviation, so each column has mean 0 and standard deviation 1. It is the usual default. - Min-max scaling (
MinMaxScaler) squeezes each column into 0 to 1. It is handy when you need a fixed range, but a single extreme value squashes everything else. - After scaling, age and salary are directly comparable even though salary started out thousands of times larger.
| Needs scaling | Does not need scaling |
|---|---|
| KNN, k-means, SVM (distance-based) | Decision trees, random forests, gradient boosting |
| Logistic and linear regression with regularisation | Plain linear regression (predictions are unchanged) |
| Neural networks |
Missing Values, Categories and Pipelines
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
# A small loan-approval table with a missing value
df = pd.DataFrame({
"income": [25000, 48000, np.nan, 81000, 30000, 62000, 55000, 20000],
"age": [23, 35, 41, 52, 29, 45, 38, 26],
"city": ["Dhaka", "Sylhet", "Dhaka", "Khulna", "Sylhet", "Dhaka", "Khulna", "Dhaka"],
"approved": [0, 1, 1, 1, 0, 1, 1, 0],
})
X, y = df.drop(columns="approved"), df["approved"]
numeric = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
prep = ColumnTransformer([
("num", numeric, ["income", "age"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression())])
model.fit(X, y)
print("Columns after encoding:", list(model.named_steps["prep"].get_feature_names_out()))
new = pd.DataFrame({"income": [40000], "age": [31], "city": ["Rajshahi"]})
print("Approval probability for a new applicant:", model.predict_proba(new)[0, 1].round(2))
Output
Columns after encoding: ['num__income', 'num__age', 'cat__city_Dhaka', 'cat__city_Khulna', 'cat__city_Sylhet']
Approval probability for a new applicant: 0.53
SimpleImputer(strategy="median")fills the missing income with the median of the training data. The median is less affected by very high incomes than the mean.OneHotEncoderturns thecitycolumn into one 0/1 column per city. Simply numbering the cities 1, 2, 3 would wrongly suggest that Khulna is “between” Dhaka and Sylhet.handle_unknown="ignore"lets the model accept a city it never saw in training, Rajshahi here, by setting all the city columns to 0 instead of crashing.ColumnTransformersends each group of columns through its own steps, then joins the results.- The outer
Pipelinechains preprocessing and the model. Callingfitlearns the medians, scaling and categories from the training data only; callingpredictapplies exactly the same transformations to new data. - The dataset is tiny and made up for illustration, so the 0.53 probability shows how the mechanics work, not a real lending decision.
Why Pipelines Prevent Leakage
If you scale the whole dataset before splitting, the scaler has already seen the test rows’ mean and spread, so test scores come out slightly too optimistic. The same applies to imputing and encoding. With a pipeline passed to cross_val_score or GridSearchCV, every fold fits its own preprocessing on its own training part, which is exactly what will happen with genuinely new data.
Other Common Steps
| Problem | Tool |
|---|---|
| Ordered categories (small, medium, large) | OrdinalEncoder with an explicit order |
| Very skewed values such as income | np.log1p or PowerTransformer |
| Many outliers | RobustScaler |
| Text | TfidfVectorizer |
| Dates | Extract parts such as month or weekday as new features |
Common Mistakes
- Fitting the scaler on all data before splitting.
- Label-encoding unordered categories as 1, 2, 3 for linear or distance-based models.
- Dropping every row with a missing value, throwing away useful data.
- Preprocessing new data by hand differently from the training data. Save and reuse the whole pipeline.
Practice Exercises
Exercise 1. Standardise the values [10, 20, 30] by hand. (Use the population standard deviation.)
Show answer
Mean = 20, standard deviation = √((100 + 0 + 100) / 3) ≈ 8.165. The results are about −1.22, 0 and 1.22.
Exercise 2. Save the fitted pipeline to a file and load it again.
Show answer
import joblib
joblib.dump(model, "loan_model.joblib")
loaded = joblib.load("loan_model.joblib")
print(loaded.predict(new))
Because preprocessing is inside the pipeline, the loaded model accepts raw data in the original format.
Frequently Asked Questions
Should I scale the target variable?
Usually not for classification. For regression it is optional; if you do, use TransformedTargetRegressor so predictions are converted back to the original units automatically.
What is the difference between fit, transform and fit_transform?
fit learns settings such as the mean from data, transform applies them, and fit_transform does both at once. Use fit_transform on training data and only transform on test data, or let a pipeline handle it.
Summary
- Scale features for distance-based and regularised models; trees do not need it.
- Impute missing values and one-hot encode unordered categories.
ColumnTransformertreats different columns differently.- Pipelines keep preprocessing consistent and prevent data leakage.
Next: K-Means Clustering.
