Data Preprocessing for Machine Learning with Python
A beginner-friendly, step-by-step guide to preparing data for machine learning using Python and scikit-learn.
We will learn how to inspect and clean data, split it into training and test sets, handle missing values, encode categorical data, scale numerical features, and combine everything into a format ready for a machine learning model.
Core workflow to remember:
Inspect → Clean → Separate → Split → Impute → Encode → Scale → Train
1. The Machine Learning Process
A machine learning project has three main stages.
Step 1: Data Preprocessing
Before training a model, prepare the data.
- Import the data: Load the dataset into your program.
- Clean the data: Fix errors, handle missing values, and make the data consistent.
- Split the data: Divide it into training and test sets.
Note: Cleaning data is an important part of real-world machine learning projects, but many courses or tutorials use pre-cleaned datasets so you can focus on learning other concepts. Real cleaning also includes removing duplicate rows, fixing wrong data types, and catching impossible values such as an age of -5.
Step 2: Modeling
Once the data is ready, build a model.
- Build the model: Choose a suitable machine learning algorithm.
- Train the model: Let the algorithm learn patterns from the training data.
- Make predictions: Use the trained model to predict outcomes for new data.
Step 3: Evaluation
After training, check how well the model performs.
- Calculate performance metrics: Measure how accurate or effective its predictions are.
- Evaluate the model: Decide whether its performance is good enough for the task.
- Check the fit: Determine whether the model has learned useful patterns and performs as expected.
2. Splitting Data into Training and Test Sets
Why do we split the data?
Imagine teaching a student using a set of practice questions and then testing them using those exact same questions. The student might perform very well because they have already seen the answers. But that does not necessarily mean they can answer new questions.
Machine learning models face a similar problem. To evaluate a model fairly, we divide our dataset into two parts:
- Training set: The data the model learns from.
- Test set: Data the model has never seen during training, used to evaluate its predictions.
Example: Predicting car sale prices
Suppose we want to predict how much a car will sell for.
We have one target and two features:
- Target (dependent variable): Sale price — what we want to predict.
- Features (independent variables): Mileage and age — the information used to make the prediction.
Let's say our dataset contains 20 cars, and we use an 80/20 split.
| Dataset | Percentage | Cars | Purpose |
|---|---|---|---|
| Training set | 80% | 16 | Teach the model patterns |
| Test set | 20% | 4 | Evaluate predictions on unseen data |
How does the process work?
- Divide the 20 cars into 16 training cars and 4 test cars.
- Train a model, such as linear regression, using the 16 training cars.
- Give the model the features of the 4 test cars and ask it to predict their sale prices.
- Compare the predicted prices with the actual prices.
Because the model did not see the test cars during training, this comparison gives us a better idea of how well it might perform on new data.
If the predictions are poor, we may need to improve the model or prepare the data differently.
3. Feature Scaling
Feature scaling makes numerical features comparable by bringing their values onto a similar scale.
Consider a dataset containing two features:
- Annual income: values in the tens of thousands.
- Age: values between approximately 20 and 60.
These features use very different numerical ranges. Some machine learning algorithms can give too much importance to features with larger numerical values.
Scaling helps address this problem.
Remember: We scale each feature (column) independently, not each row.
3.1 Normalization
Normalization, commonly performed using Min-Max scaling, transforms a feature using its minimum and maximum values.
The result typically falls between 0 and 1 for the data used to fit the scaler.
Formula:
Normalized Value = (Value - Minimum) / (Maximum - Minimum)
Let's use three values: 10, 20, and 30. The minimum is 10, and the maximum is 30.
For the value 20: (20 - 10) / (30 - 10) = 10 / 20 = 0.5
The normalized values are:
| Original value | Normalized value |
|---|---|
| 10 | 0.0 |
| 20 | 0.5 |
| 30 | 1.0 |
The smallest value becomes 0, the largest becomes 1, and the value in the middle becomes 0.5.
3.2 Standardization
Standardization changes a feature based on its mean and standard deviation.
Formula:
Standardized Value = (Value - Mean) / Standard Deviation
In simple terms:
- Subtract the mean from each value.
- Divide the result by the standard deviation.
After standardization, the training data has a mean of approximately 0 and a standard deviation of 1.
Most values often fall between -3 and 3, although outliers can fall outside this range.
What's the difference?
- Normalization: Scales values to a fixed range, usually 0 to 1 for the training data.
- Standardization: Centers values around 0 and scales them using the standard deviation. Values are not restricted to a fixed range.
3.3 Why does feature scaling matter?
Let's look at a simple example. Suppose we have information about three people:
| Person | Annual income | Age |
|---|---|---|
| Blue | $70,000 | 45 |
| Purple | $60,000 | 44 |
| Red | $52,000 | 40 |
We want to answer this question: Is Purple more similar to Blue or Red?
First, compare their differences using the original values.
| Comparison | Income difference | Age difference |
|---|---|---|
| Purple vs. Blue | $10,000 | 1 year |
| Purple vs. Red | $8,000 | 4 years |
Notice that income differences are much larger numerically than age differences. A distance-based algorithm may therefore give income too much influence and age too little influence. It's like comparing apples and oranges: the numbers are measured using different scales.
Let's normalize each column separately. For income, the minimum is $52,000, and the maximum is $70,000. For age, the minimum is 40, and the maximum is 45.
Using the normalization formula, we get:
| Person | Normalized income | Normalized age |
|---|---|---|
| Blue | 1.0 | 1.0 |
| Purple | 0.444 | 0.8 |
| Red | 0.0 | 0.0 |
Now both features use the same 0–1 scale. Let's answer the question.
A distance-based algorithm measures similarity by calculating the straight-line distance between two points: √((difference in income)² + (difference in age)²). A smaller distance means more similar.
Before scaling (raw values):
| Comparison | Distance | Result |
|---|---|---|
| Purple vs. Blue | ≈ 10,000 | Farther |
| Purple vs. Red | ≈ 8,000 | Closer |
The income difference is so large that the age difference barely registers. Purple looks more similar to Red.
After normalizing:
| Comparison | Distance | Result |
|---|---|---|
| Purple vs. Blue | ≈ 0.59 | Closer |
| Purple vs. Red | ≈ 0.92 | Farther |
Now income and age both contribute fairly, and the answer flips: Purple looks more similar to Blue.
This is the whole point of scaling. The algorithm's answer depended on the units we happened to use, not on the actual similarity between people.
Key takeaways
- Scale each numerical feature (column) independently.
- Scaling helps make features with different units and ranges comparable.
- It prevents large numerical values from dominating distance- or magnitude-based algorithms simply because of their scale.
- Scaling can still be useful when features share the same units but have very different ranges or roles.
Scaling is especially useful for:
- K-nearest neighbors (KNN)
- K-means clustering
- Support vector machines (SVM)
- Logistic regression
- Neural networks
- Principal component analysis (PCA)
Not every algorithm needs feature scaling. Tree-based algorithms, such as decision trees and random forests, generally do not.
Also, Min-Max scaling does not guarantee that future values will stay between 0 and 1. If a new value is smaller than the training minimum or larger than the training maximum, its scaled value can fall outside that range.
Standardization also does not restrict values to a fixed range.
4. Data Preprocessing Tools: Hands-On Tutorial
Now let's apply these concepts to one dataset from beginning to end. We'll create a dataset containing information about 20 customers.
Each customer has four columns:
- Country: Where the customer lives.
- Age: The customer's age.
- Salary: The customer's annual salary.
- Purchased: Whether the customer purchased a product.
Our goal is to predict whether a customer will purchase the product. This is a classification problem because the target has two possible outcomes: Yes and No.
We'll create the dataset directly in Python, so we don't need to download a file or use Google Drive.
The dataset contains some missing values to help us practice working with imperfect, real-world data:
- One missing country.
- Two missing ages.
- Two missing salaries.
What will we practice?
Using this single dataset, we'll learn how to:
- Import the required libraries.
- Create a dataset.
- Inspect and clean the data.
- Separate features (
X) and the target (y). - Split the data into training and test sets.
- Handle missing values.
- Encode categorical data.
- Apply feature scaling.
- Combine the processed features.
Important: The order matters. We split the data before fitting preprocessing tools so that information from the test set does not influence the training process.
4.1 Import the libraries
First, import the Python libraries we'll use.
| Library | Alias | Purpose |
|---|---|---|
| NumPy | np |
Work with numerical arrays and represent missing values using np.nan |
| pandas | pd |
Create and manipulate tables called DataFrames |
| Matplotlib | plt |
Create charts and visualizations (optional in this tutorial) |
| scikit-learn | — | Split data and preprocess it for machine learning |
import numpy as np
import pandas as pd
import matplotlib.pyplot as pltThe aliases np and pd are common Python conventions. You can use different names, but following these conventions makes code easier to recognize. We'll import scikit-learn tools when we first need them.
4.2 Create the dataset in Python
Instead of loading a CSV file, we'll create our dataset using a Python dictionary. Each dictionary key becomes a column name, and its list contains the values for that column. We'll use np.nan to represent missing values.
data = {
"Country": [
"France", "Spain", "Germany", "France", "Spain",
"Germany", "France", "Spain", "Germany", "France",
np.nan, "Germany", "France", "Spain", "Germany",
"France", "Spain", "Germany", "France", "Spain"
],
"Age": [
44, 27, 30, 38, np.nan,
35, 48, 29, 41, 33,
26, np.nan, 45, 31, 37,
28, 42, 34, 39, 25
],
"Salary": [
72000, 48000, 54000, 61000, 52000,
np.nan, 83000, 45000, 69000, 58000,
42000, 76000, np.nan, 49000, 65000,
47000, 79000, 56000, 68000, 43000
],
"Purchased": [
"No", "Yes", "No", "No", "Yes",
"Yes", "No", "Yes", "No", "Yes",
"Yes", "No", "No", "Yes", "No",
"Yes", "No", "Yes", "No", "Yes"
]
}
dataset = pd.DataFrame(data)
datasetThe last line displays the DataFrame in a notebook. Let's understand the columns.
| Column | Meaning | Type |
|---|---|---|
| Country | Where the customer lives (France, Spain, Germany) | Categorical feature; 1 missing |
| Age | Customer age in years | Numerical feature; 2 missing |
| Salary | Annual salary | Numerical feature; 2 missing |
| Purchased | Whether the customer bought the product (Yes/No) | Target |
A DataFrame is simply a table with rows and named columns.
4.3 Inspect the data and clean inconsistent text
Before preparing the data for a model, we need to understand what it contains.
Run the following commands:
dataset.head(10) # Display the first 10 rows
print("Shape:", dataset.shape) # Number of rows and columns
dataset.info() # Column names, data types, non-null counts
dataset.describe() # Summary statistics for numeric columns
print(dataset.isna().sum()) # Missing values in each column
print(dataset["Purchased"].value_counts()) # Count Yes and NoLet's understand what each command does.
head(10)displays the first ten rows.shapetells us the number of rows and columns.info()shows each column's data type and how many values are not missing.describe()gives summary statistics for numerical columns.isna().sum()counts missing values in each column.value_counts()counts how often each target label appears.
What should you notice?
- The dataset has 20 rows and 4 columns, so its shape is
(20, 4). Agehas 18 non-missing values, meaning 2 are missing.Salaryalso has 18 non-missing values, meaning 2 are missing.Countryhas 19 non-missing values, meaning 1 is missing.describe()reports a count of 18 forAgeandSalarybecause it excludes missing values.CountryandPurchasedcontain text.- The target contains 10
Yesvalues and 10Novalues.
Clean inconsistent text
Real-world data often contains different spellings or formatting for the same value.
For example, these values all refer to France:
France
france
france
FRANCEHowever, a computer may treat them as different categories. To practice cleaning text, we'll deliberately introduce two inconsistencies.
# Deliberately introduce inconsistent spellings for practice
dataset.loc[0, "Country"] = " france "
dataset.loc[2, "Country"] = "GERMANY"
print(dataset["Country"].value_counts(dropna=False))Now, France, france, and GERMANY appear as separate categories. The missing country is also included in the count because we used dropna=False.
We can standardize the text using two pandas string methods:
dataset["Country"] = dataset["Country"].str.strip().str.title()
print(dataset["Country"].value_counts(dropna=False))Here's what happens:
.str.strip()removes spaces at the beginning and end of a string..str.title()converts the text to title case, such asfrancetoFrance.- Missing values remain missing.
After cleaning, the counts are France: 7, Spain: 6, Germany: 6, and 1 missing value.
Why isn't this data leakage?
These cleaning rules work on each value independently. They do not calculate statistics using other rows.
For example, changing " france " to "France" produces the same result whether the row belongs to the training set or test set.
However, calculating an average or learning a list of categories from the entire dataset is different. Those operations use information from multiple rows.
Also, remember that text normalization must match the meaning of your data. Changing capitalization won't fix every spelling mistake, abbreviation, or genuinely different category.
Checkpoint: You should now understand the dataset's size, its column types, its missing values, and how to standardize inconsistent country names.
4.4 Separate features (X) and target (y)
Before training a model, we need to identify two things:
- Features (
X): The information the model uses to make predictions. - Target (
y): The value the model must predict.
In our dataset:
- Features:
Country,Age, andSalary. - Target:
Purchased.
We don't include Purchased in X because it is the answer we want the model to learn to predict.
target_column = "Purchased"
X = dataset.drop(columns=[target_column]).copy()
y = dataset[target_column].copy()
# Positional alternative (assumes the target is the last column):
# X = dataset.iloc[:, :-1].copy()
# y = dataset.iloc[:, -1].copy()
print("Features:", X.columns.tolist())
print("X shape:", X.shape) # (20, 3)
print("y shape:", y.shape) # (20,)Let's understand the code.
drop(columns=[target_column])removes the target column from the features..copy()creates an independent copy of the data.Xcontains three feature columns.ycontains one target value for each customer.
We select the target by its name rather than assuming it is the last column. This is safer because column order can change.
We also keep X as a DataFrame so we can select columns by name in later steps.
4.5 Split the data into training and test sets
Now we divide the data into two sets. We'll use 80% for training and 20% for testing.
We must split the data before imputing missing values, encoding categories, or scaling features.
Otherwise, the test set could influence the information learned during preprocessing.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=1,
stratify=y
)
# Independent copies avoid SettingWithCopyWarning when editing columns
X_train = X_train.copy()
X_test = X_test.copy()
print("X_train:", X_train.shape) # (16, 3)
print("X_test:", X_test.shape) # (4, 3)
print(y_train.value_counts())
print(y_test.value_counts())Let's understand the arguments.
| Argument | Meaning |
|---|---|
X, y |
Features and target |
test_size=0.2 |
Reserve 20% of the rows for testing |
random_state=1 |
Makes the random split reproducible |
stratify=y |
Preserve the target's class proportions as closely as possible |
Because we have 20 customers:
- The training set contains 16 customers.
- The test set contains 4 customers.
Our dataset has 10 Yes and 10 No labels. Stratification gives us 8 Yes and 8 No in the training set, and 2 Yes and 2 No in the test set.
This is especially useful with small or imbalanced datasets, where a random split might leave very few examples of one class in the test set.
For time-ordered data, such as forecasting future sales, we should split chronologically instead of randomly.
Where did the missing values go?
After splitting, the missing values are distributed between the two sets.
- Training set: 1 missing
Country, 1 missingAge, and 2 missingSalaryvalues. - Test set: 1 missing
Agevalue.
Both sets contain missing values, so we'll need to handle them.
Note: These exact counts, and the learned averages later in this tutorial, depend on random_state=1. If you change the seed, the missing values will land differently, and your numbers will differ. If you follow this tutorial exactly (same data, same seed), the numbers shown below are what you should see.
Understanding data leakage
Data leakage happens when information that should not be available during training influences the model or its evaluation.
For example, suppose we calculate the average age using all 20 customers before splitting the data.
That average includes information from the test customers. If we use it to fill missing ages in the training data, the test set has influenced the training process.
The same problem can happen when learning scaling statistics or category lists from the entire dataset.
Remember: Split first. Fit preprocessing tools on the training data only. Use those fitted tools to transform both the training and test data.
4.6 Handle missing values
Many machine learning algorithms cannot work directly with missing values represented by NaN. One common solution is imputation: replacing missing values with an estimated or specified value.
First, let's check which values are missing in each set.
print("Missing values in training features:")
print(X_train.isna().sum())
print("\nMissing values in test features:")
print(X_test.isna().sum())We must fill missing values in both sets, but the replacement values must be learned from the training set only.
Choose an imputation strategy
| Strategy | What it uses to fill missing values | Common use |
|---|---|---|
mean |
Average of the observed values | Numerical data without strong skew or extreme outliers |
median |
Middle value of the observed values | Numerical data with skew or outliers |
most_frequent |
Most common value | Categorical or numerical data |
constant |
A value you specify | A placeholder such as "Unknown" |
For Age and Salary, we'll use the mean. If salaries contained a few extremely high values, the median might be a better choice because it is less affected by extreme values.
Impute missing numerical values
We'll use scikit-learn's SimpleImputer.
from sklearn.impute import SimpleImputer
numeric_columns = ["Age", "Salary"]
imputer = SimpleImputer(strategy="mean")
imputer.fit(X_train[numeric_columns]) # Learn means from training data only
print("Learned means:", imputer.statistics_)
X_train[numeric_columns] = imputer.transform(X_train[numeric_columns])
X_test[numeric_columns] = imputer.transform(X_test[numeric_columns])Let's break this down.
SimpleImputer(strategy="mean")creates an imputer that replaces missing values with column averages.fit()calculates the averages using the training data.statistics_shows the learned averages.transform()fills missing values using those averages.
With random_state=1, the learned means are approximately:
- Age: 35.4 years.
- Salary: 58,285.71.
The customer with a missing age in the test set receives the training-set mean of approximately 35.4.
Notice that we did not calculate a new average from the test set.
Impute the missing country
Country is categorical, so calculating a numerical average would not make sense. Instead, we'll use the most frequent country in the training set.
categorical_columns = ["Country"]
categorical_imputer = SimpleImputer(strategy="most_frequent")
categorical_imputer.fit(X_train[categorical_columns])
print("Most frequent country:", categorical_imputer.statistics_) # ['France']
X_train[categorical_columns] = categorical_imputer.transform(X_train[categorical_columns])
X_test[categorical_columns] = categorical_imputer.transform(X_test[categorical_columns])The imputer learns that France is the most frequent country among the training customers. It uses France to fill the missing country.
Another option is to use a fixed placeholder such as "Unknown":
SimpleImputer(strategy="constant", fill_value="Unknown")This can be useful when the fact that a value is unknown may itself be informative.
Check that the missing values are gone
print(X_train.isna().sum().sum()) # Expect 0
print(X_test.isna().sum().sum()) # Expect 0Both results should be 0, meaning no missing values remain in the feature sets.
Understanding fit(), transform(), and fit_transform()
These three methods are important throughout scikit-learn.
| Method | What it does |
|---|---|
fit(data) |
Learns information from the supplied data |
transform(data) |
Applies the information learned earlier |
fit_transform(data) |
Learns from the data and transforms it in one step |
For training data, fit_transform() is often convenient. For test data, use transform() with the already-fitted tool. Never fit a separate imputer, encoder, or scaler on the test set.
4.7 Encode categorical data
Machine learning algorithms often require numerical inputs. This means we need to convert categorical text into numbers.
Before choosing an encoding method, understand the type of category.
- Nominal data: Categories have no natural order. For example, France, Spain, and Germany.
- Ordinal data: Categories have a meaningful order. For example, Beginner, Intermediate, and Advanced.
Our dataset contains nominal data in the Country column. It does not contain an ordinal feature.
One-hot encode Country
One-hot encoding creates a separate binary column for each category. For our three countries, the result looks like this:
| Country | France | Germany | Spain |
|---|---|---|---|
| France | 1 | 0 | 0 |
| Spain | 0 | 0 | 1 |
| Germany | 0 | 1 | 0 |
Each country is represented by a pattern of zeros and ones. For example, France becomes [1, 0, 0].
Why not simply assign France = 1, Germany = 2, and Spain = 3?
Because these numbers might suggest that the countries have a natural order or that the difference between them has a meaningful numerical interpretation. They don't.
Let's implement one-hot encoding.
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
encoder.fit(X_train[["Country"]]) # Learn categories from training data only
X_train_country = encoder.transform(X_train[["Country"]])
X_test_country = encoder.transform(X_test[["Country"]])
print("Learned categories:", encoder.categories_)
print(X_train_country[:5])The encoder learns the categories present in the training data: France, Germany, and Spain. It creates three output columns in that order.
Notice that we use double brackets:
X_train[["Country"]]The double brackets select a DataFrame containing one column. The encoder expects a two-dimensional table rather than a one-dimensional Series.
Why use handle_unknown="ignore"?
Imagine a future customer has a country that wasn't present in the training data. Without handle_unknown="ignore", the encoder would raise an error when it encountered that country. With this option, the unknown country is represented by zeros across the encoded country columns.
However, the model cannot learn a separate effect for a country it never encountered during training.
The argument sparse_output=False tells scikit-learn to return a regular NumPy array. This is convenient for our small example.
Version note: sparse_output requires scikit-learn 1.2 or later. In older versions (before 1.2), the equivalent argument is sparse=False. Section 6's OneHotEncoder uses the default (sparse) output, which is explained there.
Encode the target: Purchased
Our target contains text labels:
No
YesWe'll convert these labels to integers using LabelEncoder.
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
label_encoder.fit(y_train)
y_train_encoded = label_encoder.transform(y_train)
y_test_encoded = label_encoder.transform(y_test)
print("Target classes:", label_encoder.classes_) # ['No' 'Yes']
print(y_train_encoded)
print(y_test_encoded)The encoder sorts the labels alphabetically:
Nobecomes0.Yesbecomes1.
Always inspect classes_ instead of assuming which label corresponds to which number.
We fit the encoder using the training labels, then transform both sets.
If the test set contains a target class that wasn't present in the training set, transform() will raise an error. That situation needs investigation because the model has not learned that class.
Ordinal encoding
Ordinal encoding is used when categories have a meaningful order. Our dataset doesn't contain an ordinal feature, but here's an example of how to define the order:
from sklearn.preprocessing import OrdinalEncoder
# Example only: our dataset has no ordered column
ordinal_encoder = OrdinalEncoder(
categories=[["Beginner", "Intermediate", "Advanced"]]
)This explicitly defines the order:
Beginner < Intermediate < AdvancedDon't use ordinal encoding just because a column contains text. Country names do not have an inherent order.
Which encoding tool should you use?
OneHotEncoder: For nominal input features, such as country.OrdinalEncoder: For input features with a meaningful order.LabelEncoder: For target labels (y), such asPurchased, rather than ordinary input features.
4.8 Apply feature scaling
We've handled missing values and encoded the country names. Now we'll scale the numerical features.
Our numerical columns are:
numeric_columns = ["Age", "Salary"]Age and salary have very different numerical ranges. For example, age may be around 25–48, while salary may be between 42,000 and 83,000. A distance-based algorithm could give salary too much influence simply because its numbers are larger. We'll use standardization to put the two numerical features on a comparable scale.
Formula:
The mean and standard deviation are learned from the training data.
- A value above the training mean becomes positive.
- A value below the training mean becomes negative.
- A value equal to the mean becomes zero.
Let's apply standardization.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train[numeric_columns]) # Learn mean and std from training data only
X_train_scaled = scaler.transform(X_train[numeric_columns])
X_test_scaled = scaler.transform(X_test[numeric_columns])
print("Scaled training values:")
print(X_train_scaled[:5].round(2))
print("Scaled test values:")
print(X_test_scaled.round(2))What should you notice?
Think of the scaler as a ruler that you build from the training data.
Building the ruler (fit on training data): The scaler looks at the training customers and learns two things: the average age (about 35.4) and the typical spread (the standard deviation). It then converts every age into "how far is this from 35.4, measured in units of spread?"
Now, what to notice:
- The training data ends up with a mean of 0 and a standard deviation of 1. The ruler was built from these exact customers, so it centers them perfectly. This is expected.
- The test data does NOT end up with a mean of exactly 0. The test customers are different people. Their average age is not exactly 35.4, so after using the same ruler, their average won't be exactly 0. A test mean of about -0.19 for age means the test customers are slightly younger than the training average. A test mean of about 0.41 for salary means they earn slightly more than the training average. This is normal.
- We use the training ruler on test data so the same value always means the same thing. Suppose the training ruler turns age 40 into a small positive number. The model learns what that number means. If we built a new ruler from the test data, the same age 40 would turn into a different number. It would be like measuring one person in centimeters and another in inches.
- One-hot country columns are left unscaled. They are already 0 or 1, which is a small, comparable range. Scaling them would only make them harder to read.
- We must not fit a separate scaler on the test data. First, it breaks the "same ruler" rule from point 3. Second, it would force the test mean to 0 and hide the fact that the test group differs from the training group. The test set exists to imitate new, unseen data, so those differences are exactly what we want it to show.
In one sentence: The scaler learns its "ruler" (mean and spread) from the training data only, and we use that same ruler on the test data. The test data won't come out perfectly centered at 0, and that's fine: it just means the test customers differ a bit from the training customers.
Min-Max scaling
We can also use Min-Max scaling to transform numerical features into a 0–1 range based on the training minimum and maximum.
Formula:
In scikit-learn, we use MinMaxScaler.
from sklearn.preprocessing import MinMaxScaler
minmax_scaler = MinMaxScaler()
minmax_scaler.fit(X_train[numeric_columns])
X_train_minmax = minmax_scaler.transform(X_train[numeric_columns])
X_test_minmax = minmax_scaler.transform(X_test[numeric_columns])
print(X_test_minmax.round(2))The training values for each feature span from 0 to 1.
However, test values are not guaranteed to stay in that range. A test value below the training minimum can become negative, and a value above the training maximum can become greater than 1.
Min-Max scaling vs. Standardization
| Property | Min-Max scaling | Standardization |
|---|---|---|
| Formula | Subtract minimum and divide by range | Subtract mean and divide by standard deviation |
| Training range | 0 to 1 | No fixed range |
| Training mean | Not generally 0 | Approximately 0 |
| Affected by outliers | Yes | Yes |
| scikit-learn tool | MinMaxScaler |
StandardScaler |
Neither method is always better. The right choice depends on the data and the algorithm.
Which algorithms benefit from scaling?
Scaling is useful for many algorithms, including:
- K-nearest neighbors (KNN)
- K-means clustering
- Support vector machines (SVM)
- Logistic regression
- Neural networks
- Principal component analysis (PCA)
Tree-based algorithms, such as decision trees and random forests, generally do not need feature scaling.
See data leakage in action
Let's compare two scalers:
- A scaler fitted using all 20 customers.
- The correct scaler, fitted using only the training customers.
# Incorrect: test customers influence the scaler's statistics
leaky_scaler = StandardScaler().fit(X[numeric_columns])
print("Leaky means: ", leaky_scaler.mean_)
print("Correct means:", scaler.mean_)With random_state=1, the scaler fitted on the full dataset learns a mean age of approximately 35.1 and a mean salary of approximately 59,278.
The correct scaler learns its means from the training set: approximately 35.4 for age and 58,286 for salary.
The difference is small in this example, but the principle is important.
When we fit a scaler on the entire dataset, test customers influence the statistics used to transform the training data.
The same problem can occur with imputers, encoders, and other preprocessing tools that learn information from data.
The rule remains the same: fit on training data only, then transform both sets.
4.9 Combine the processed features
So far, we've prepared the country features and numerical features separately.
We now have:
X_train_country: One-hot encoded countries for the training set.X_test_country: One-hot encoded countries for the test set.X_train_scaled: Standardized numerical features for the training set.X_test_scaled: Standardized numerical features for the test set.
We need to combine the country and numerical features into one array for each set. We'll use NumPy's hstack(), which places arrays side by side.
X_train_processed = np.hstack([X_train_country, X_train_scaled])
X_test_processed = np.hstack([X_test_country, X_test_scaled])
feature_names = list(encoder.get_feature_names_out(["Country"])) + numeric_columns
print(pd.DataFrame(X_train_processed, columns=feature_names).round(2).head())
print("Training shape:", X_train_processed.shape) # (16, 5)
print("Test shape:", X_test_processed.shape) # (4, 5)
print("Missing in training:", np.isnan(X_train_processed).sum())
print("Missing in test:", np.isnan(X_test_processed).sum())The resulting feature arrays contain five columns:
Country_FranceCountry_GermanyCountry_SpainAgeSalary
The age and salary columns contain standardized values. The training set has 16 rows and 5 columns, while the test set has 4 rows and 5 columns. Both sets must have the same feature columns in the same order so the model receives consistent inputs. The missing-value counts should both be zero.
Verify the results
We can add a few checks to catch mistakes before training the model.
assert X_train_processed.shape[0] == len(y_train_encoded)
assert X_test_processed.shape[0] == len(y_test_encoded)
assert np.isfinite(X_train_processed).all()
assert np.isfinite(X_test_processed).all()
print("All verification checks passed.")Let's understand these checks:
- The number of training feature rows must match the number of training labels.
- The number of test feature rows must match the number of test labels.
np.isfinite()checks that the arrays contain noNaNor infinite values.
If all checks pass, the code prints:
All verification checks passed.You now have numerical features and target labels ready for a classification model:
X_train_processedX_test_processedy_train_encodedy_test_encoded
The preprocessing stage is complete.
5. Final Review
Let's review the complete workflow and the tools we used.
| Step | Tool or method | Purpose |
|---|---|---|
| Load data | pd.read_csv() |
Load a CSV file (we created our dataset in code instead) |
| Inspect data | head(), info(), describe() |
Understand the dataset |
| Clean data | .str.strip(), .str.title() |
Standardize inconsistent text |
| Separate data | X, y |
Identify features and target |
| Split data | train_test_split() |
Keep test data separate from training |
| Impute missing values | SimpleImputer |
Replace missing feature values |
| Encode categories | OneHotEncoder |
Convert nominal features into binary columns |
| Encode target labels | LabelEncoder |
Convert target classes into integers |
| Scale features | StandardScaler |
Standardize numerical features |
| Combine features | np.hstack() |
Assemble the processed feature arrays |
The most important rule
Fit preprocessing tools on the training data, then use those same fitted tools to transform both the training and test data.
This prevents preprocessing data leakage and helps make your model evaluation representative of performance on unseen data.
In this tutorial, we performed every step manually so you could understand what each tool learns and how leakage can happen.
For every imputer, encoder, and scaler:
- Call
fit()on the training data. - Use
transform()on the training data and test data. - Never learn preprocessing statistics from the test set.
6. Doing It All in One Object: Pipeline and ColumnTransformer
In section 4, we did every step by hand so we could see what each tool learns. In real projects, you bundle these steps into one object. This has three benefits:
- Less code: one
fit()and onepredict()instead of many separate steps. - No leakage by accident: when you call
fit()on training data, every step learns from the training data only. When you score on test data, every step only transforms. - Safe cross-validation: each fold gets fitted separately. Doing it by hand makes it easy to leak here.
Two tools to know:
| Tool | What it does |
|---|---|
Pipeline |
Chains steps in order, where each step's output feeds the next |
ColumnTransformer |
Applies different preprocessing to different columns, such as numbers vs. categories |
The idea:
Numeric columns → impute (mean) → scale
Categorical columns → impute (most frequent) → one-hot encode
↓
combine → modelfrom sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder
from sklearn.linear_model import LogisticRegression
numeric_columns = ["Age", "Salary"]
categorical_columns = ["Country"]
numeric_pipeline = Pipeline([
("impute", SimpleImputer(strategy="mean")),
("scale", StandardScaler()),
])
categorical_pipeline = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
preprocessor = ColumnTransformer([
("num", numeric_pipeline, numeric_columns),
("cat", categorical_pipeline, categorical_columns),
])
model = Pipeline([
("preprocess", preprocessor),
("classifier", LogisticRegression()),
])
# Use the RAW split from section 4.5 (not the manually processed data).
# If you already ran section 4 in this notebook, re-create the raw split first:
from sklearn.model_selection import train_test_split
X_raw = dataset.drop(columns=["Purchased"]).copy()
y_raw = dataset["Purchased"].copy()
X_train_raw, X_test_raw, y_train_raw, y_test_raw = train_test_split(
X_raw,
y_raw,
test_size=0.2,
random_state=1,
stratify=y_raw
)
X_train_raw = X_train_raw.copy()
X_test_raw = X_test_raw.copy()
# Encode the target (optional for scikit-learn classifiers, but kept for clarity)
label_encoder = LabelEncoder().fit(y_train_raw)
y_train_enc = label_encoder.transform(y_train_raw)
y_test_enc = label_encoder.transform(y_test_raw)
model.fit(X_train_raw, y_train_enc) # every step fits on training data only
print(model.score(X_test_raw, y_test_enc)) # test data is only transformedThings to notice:
- We pass the raw
X_train_raw, which still has missing values and text. The pipeline handles all of it. ColumnTransformerputs the output columns in the order you list the transformers. Here that'sAge,Salary, then the three country columns, which differs from our manual version. Check the exact names withpreprocessor.get_feature_names_out().- The encoder in this pipeline uses its default sparse output (no
sparse_output=False).LogisticRegressionaccepts sparse input, so no conversion is needed. If you need a dense array, passsparse_output=FalsetoOneHotEncoder(scikit-learn 1.2+) orsparse=False(older versions). - If the score happens to be
1.0on 4 test customers, that means almost nothing. The test set is tiny, so don't read anything into it. - The target still needs encoding separately, because
yisn't part of the feature pipeline.
Rule of thumb: learn the steps by hand, then use pipelines for real work.
7. Practice Exercises
Try these exercises to check your understanding.
Exercise 1: Inspect the dataset
Display the first ten rows, count the rows and columns, and report the number of missing values in each column.
Hint: Use head(10), shape, and isna().sum().
Exercise 2: Separate features and target
Create X and y. Explain why Purchased should not be included in X.
Hint: Use drop(columns=["Purchased"]).
Exercise 3: Compare imputation methods
Fit mean and median imputers on the training Salary column. Compare the values they learn.
Hint: Try SimpleImputer(strategy="mean") and SimpleImputer(strategy="median").
Exercise 4: Experiment with encoding
Inspect the categories learned by OneHotEncoder. Explain how the encoded output represents each country and why assigning arbitrary integers to country names can be misleading.
Hint: Compare encoder.categories_ with the order of the output columns.
Exercise 5: Compare scaling methods
Apply MinMaxScaler and StandardScaler to Age and Salary. Compare the training outputs and explain why the scaled test data may not have a mean of exactly zero.
Hint: Fit each scaler on the training features only.
Exercise 6: Demonstrate data leakage
Compare a scaler fitted on the entire dataset with one fitted on the training set only.
Hint: Inspect scaler.mean_ and explain why test data must not influence the scaling statistics.
Exercise 7: Clean more text
Add the values " SPAIN" and "spain " to the Country column and standardize them.
Hint: Use .str.strip() and .str.title(), then check value_counts().
Final Takeaway
Data preprocessing is more than converting everything into numbers.
It means preparing data so that:
- Missing values are handled appropriately.
- Text values are consistent.
- Categorical features are encoded correctly.
- Numerical features are scaled when necessary.
- The meaning of the data is preserved.
- Test data does not influence the training process.
The exact preprocessing choices depend on your dataset, the meaning of each feature, and the machine learning algorithm you plan to use.
After training, evaluate the model using metrics appropriate for the problem. If the classes are imbalanced, examine precision, recall, and F1 score alongside accuracy.
Remember the workflow:
Inspect → Clean → Separate → Split → Impute → Encode → Scale → Train