Preparing Data for Machine Learning: A Practical Introduction to Data Preprocessing

Before a machine can learn from data, we need to make sure the data is ready to be learned from.
In our previous article, we explored the difference between training data and test data. We learned why a model should be evaluated using examples it hasn't already seen and why keeping these two sets separate matters.
But there's another question we need to answer before we start training our first machine learning model:
What happens when the data itself isn't ready for the model?
Imagine we're building a machine learning system that predicts house prices.
We collect information about thousands of houses. Each house has a collection of characteristics: its size, number of bedrooms, location, property type, age, and so on. We also have the price each house was sold for.
At first glance, this looks like everything we need. We have examples, information about those examples, and the answers we want the machine to learn to predict.
But real-world data is rarely that convenient.
Some houses might have missing information. Locations might be recorded as text. Numerical values might use completely different scales. Some columns might contain information that isn't useful for predicting prices. Others might contain information that would make our model's job suspiciously easy.
Feeding this data directly into a machine learning algorithm without examining or preparing it can lead to problems.
This is where data preprocessing comes in.
In this article, we'll work through the process of preparing a dataset for machine learning using Python, pandas, and scikit-learn. We'll continue with our house-price prediction example and gradually turn a raw dataset into something a machine learning model can work with.
Let's get started.
What is data preprocessing?
Data preprocessing is the process of preparing raw data so it can be used effectively by a machine learning model.
It involves examining the information we have, identifying problems, and applying appropriate transformations.
Depending on the dataset and the problem we're solving, this might involve:
- Handling missing values.
- Removing or correcting inconsistent information.
- Converting categorical information into numerical representations.
- Scaling numerical features.
- Creating new features from existing ones.
- Selecting relevant features.
- Separating the input features from the value we want to predict.
The important thing to understand is that preprocessing isn't a single operation. It's a collection of decisions and transformations that help make our data suitable for a particular machine learning task.
And these decisions matter.
A model doesn't understand data in the same way a human does. It doesn't automatically know what a neighbourhood name means, how to interpret an empty cell, or why a number such as 500 might represent a completely different quantity from 500,000.
We need to prepare that information appropriately.
Let's see what this looks like.
Let's examine our dataset
Suppose we've collected information about houses sold in different neighbourhoods.
Our dataset might look something like this:
| Size (sq ft) | Bedrooms | Bathrooms | Neighbourhood | Property type | Sale price |
|---|---|---|---|---|---|
| 1,200 | 2 | 2 | Lekki | Apartment | ₦45m |
| 1,800 | 3 | 2 | Ikeja | Detached | ₦72m |
| 950 | 2 | 1 | Yaba | Apartment | ₦32m |
| 2,400 | 4 | 3 | Lekki | Detached | ₦110m |
| 1,500 | 3 | Missing | Ikeja | Apartment | ₦58m |
The values above are illustrative, not observations from a real property dataset.
We can already identify several types of information.
Numerical information:
- Size.
- Number of bedrooms.
- Number of bathrooms.
- Sale price.
Categorical information:
- Neighbourhood.
- Property type.
The sale price is also special because it's what we're trying to predict. This is our label, or target variable, while the other columns are potential features.
Remember the distinction from our earlier discussion: features are the information a model uses to make a prediction, while the label is the answer we want it to learn to predict.
Let's load a dataset into pandas.
import pandas as pd
df = pd.read_csv("houses.csv")
print(df.head())
The read_csv() function loads a CSV file into a pandas DataFrame.
A DataFrame is essentially a table made up of rows and columns. Each row represents an observation (in our case, a house), while each column represents a characteristic of that observation.
The head() method displays the first five rows by default. It's a convenient way to get an initial look at the dataset.
But looking at the first few rows isn't enough. We need to understand what we're working with.
Exploring the dataset
Pandas provides several useful methods for inspecting a dataset.
Check its structure:
df.info()
This shows us the number of entries, column names, data types, and how many non-missing values each column contains.
Get basic numerical statistics:
df.describe()
This provides information such as the mean, standard deviation, minimum, maximum, and quartiles of numerical columns.
Check for missing values:
df.isna().sum()
This counts the missing values in each column.
Check for duplicate rows:
df.duplicated().sum()
This tells us how many rows are exact duplicates.
These small checks give us a better understanding of the dataset before we start transforming anything.
However, finding a problem doesn't automatically tell us how to fix it. We need to understand what the problem means and whether a particular transformation makes sense for our prediction task.
Let's look at some common examples.
Handling missing values
One of the most common problems with real-world datasets is missing information.
A house might have its size and number of bedrooms recorded, but its bathroom count could be missing. Another house might have no recorded property age.
In pandas, missing values are commonly represented as NaN.
Why is this a problem?
Many machine learning algorithms cannot work directly with missing numerical values. Even when a library provides some support for missing data, we shouldn't assume that leaving those values untouched is always appropriate.
We need to decide how to handle them.
There are several approaches.
Option 1: Remove rows with missing values
One approach is to remove observations containing missing values.
df.dropna()
For example, if a row is missing the number of bedrooms, we could remove that entire row.
This is straightforward, but it has a disadvantage: we lose information.
Imagine collecting information about 10,000 houses and discovering that 2,000 of them have at least one missing value.
Removing every affected row means throwing away a significant portion of the dataset.
That might not be necessary.
There are situations where removing rows is reasonable, especially when only a small number of observations are affected and the missingness doesn't introduce a serious bias. But it shouldn't be our automatic response to every missing value.
Option 2: Fill in missing values
Another approach is to replace missing values with estimated values. This is called imputation.
For numerical columns, common choices include the mean and median.
The mean is the average of the available values.
The median is the middle value after arranging the available values in ascending order.
For example, consider these property sizes:
800, 900, 1,000, 1,100, 5,000
The mean is 1,760, while the median is 1,000.
Notice how the unusually large value of 5,000 pulls the mean upwards.
This is one reason the median is often a useful choice when numerical data contains extreme values.
We can calculate the median of a column using pandas:
median_size = df["size_sqft"].median()
df["size_sqft"] = df["size_sqft"].fillna(median_size)
For categorical columns, we might fill missing values using the most frequent category.
most_common = df["neighbourhood"].mode()[0]
df["neighbourhood"] = df["neighbourhood"].fillna(most_common)
The mode() method returns the most frequently occurring value.
There are other strategies too. Sometimes it's better to assign a category such as "Unknown" rather than guess which category a missing observation belongs to.
The right approach depends on the meaning of the information and why it's missing.
One important rule: Don't calculate these replacement values using the entire dataset before separating your training and test data. We'll return to this when we discuss data leakage.
Converting categorical data into numbers
Let's return to our house-price dataset.
We have a column called neighbourhood:
| Neighbourhood |
|---|
| Lekki |
| Ikeja |
| Yaba |
| Lekki |
| Ikeja |
To us, these are meaningful locations.
But many machine learning algorithms expect numerical inputs. They don't automatically understand that Lekki, Ikeja, and Yaba represent different neighbourhoods.
We need a way to represent these categories numerically.
One common technique is one-hot encoding.
Understanding one-hot encoding
One-hot encoding converts each category into a separate binary column.
Let's say our neighbourhood column contains three unique categories:
- Lekki
- Ikeja
- Yaba
We can represent them using three new columns:
| Neighbourhood | Lekki | Ikeja | Yaba |
|---|---|---|---|
| Lekki | 1 | 0 | 0 |
| Ikeja | 0 | 1 | 0 |
| Yaba | 0 | 0 | 1 |
| Lekki | 1 | 0 | 0 |
A value of 1 indicates the category represented by that column. A value of 0 indicates that it isn't the category for that observation.
This gives us a numerical representation without pretending that one neighbourhood is greater than another.
Why not simply assign Lekki = 1, Ikeja = 2, and Yaba = 3?
Because a numerical assignment can introduce a relationship that doesn't exist.
A model might interpret the difference between 1 and 3 as greater than the difference between 1 and 2, even though these numbers are just labels for locations.
One-hot encoding avoids introducing that artificial ordering.
Implementing one-hot encoding
Pandas provides a convenient method:
pd.get_dummies(df, columns=["neighbourhood"])
This creates new columns for the different neighbourhood categories.
For a machine learning workflow, scikit-learn also provides OneHotEncoder, which we'll use later when we assemble our preprocessing pipeline.
One-hot encoding is particularly useful for categories that don't have a meaningful order, such as neighbourhoods, property types, colours, and product categories.
There are other encoding techniques for different situations, but one-hot encoding is a good starting point.
Why do numerical features sometimes need scaling?
Consider two features in our house-price dataset:
| Feature | Example value |
|---|---|
| Number of bedrooms | 3 |
| Size in square feet | 1,800 |
Both are numerical, but their ranges are very different.
Bedrooms might typically range from 1 to 6, while property size could range from a few hundred to several thousand.
Does this difference matter?
For some machine learning algorithms, it does.
Algorithms that rely on distances or are sensitive to the size of numerical values can be affected when features operate on very different scales.
For example, consider an algorithm that calculates how close two houses are to each other based on their features. The difference in property size could dominate the distance calculation simply because its numerical values are much larger than the bedroom counts.
Feature scaling helps address this by transforming numerical features so they operate on more comparable scales.
Two common approaches are standardisation and normalisation.
Standardization
Standardization transforms a numerical feature using its mean and standard deviation.
The formula is:
Where:
- $x$ is the original value.
- \(\mu\) is the mean of the feature.
- \(\sigma\) is its standard deviation.
- $z$ is the transformed value.
The resulting feature has a mean of approximately zero and a standard deviation of approximately one, when calculated on the data used to fit the transformation.
For example, a house size of 1,800 square feet might become a standardised value of 0.7, depending on the distribution of house sizes in the training data.
The value is no longer expressed in square feet. It tells us how far that observation is from the average, measured in standard deviations.
Scikit-learn provides StandardScaler for this transformation.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_data = scaler.fit_transform(df[["size_sqft", "bedrooms"]])
Normalization
Another common approach is min-max scaling.
It transforms values into a specified range, often between 0 and 1.
Here, the smallest observed value becomes 0 and the largest becomes 1.
Scikit-learn provides MinMaxScaler for this.
Which method should we use?
There isn't one universal answer. The choice depends on the algorithm, the distribution of the data, and the problem we're solving.
Also, not every algorithm needs feature scaling. Tree-based models, such as decision trees and random forests, are generally much less sensitive to differences in feature scales.
For now, remember that scaling is a way of making numerical features more comparable, not a transformation that must be applied to every dataset.
We'll explore its importance further when we get to gradient descent.
Feature engineering: Creating useful information
So far, we've mostly been cleaning or transforming information that already exists in our dataset.
But what if we could create additional information that makes the data more useful?
This is called feature engineering.
Feature engineering involves creating new features or transforming existing ones to represent information in a way that may help a model learn useful patterns.
Let's use our house-price example.
Suppose our dataset contains:
year_builtsale_year
We could create a new feature called house_age:
df["house_age"] = df["sale_year"] - df["year_built"]
Instead of asking a model to work out the relationship between two separate year columns, we've explicitly provided the age of the house at the time of sale.
Another example might involve a property's size and number of bedrooms.
We could calculate the average floor area per bedroom:
df["area_per_bedroom"] = (
df["size_sqft"] / df["bedrooms"]
)
This gives us another way to describe the property.
Does creating these features automatically improve our model?
No.
A new feature is only useful if it provides relevant information. Poorly designed features can introduce noise, redundancy, or misleading relationships.
Feature engineering requires us to think about the problem we're solving and what information might help a model make better predictions.
It's not about creating as many columns as possible. It's about creating useful representations of the information we already have.
Feature selection: Do we need every column?
Imagine our dataset contains the following columns:
- Size.
- Bedrooms.
- Bathrooms.
- Neighbourhood.
- Property type.
- Property owner's phone number.
- Listing description ID.
- Sale price.
Should we give all these columns to our model?
Not necessarily.
Some columns may have little predictive value. Others might simply identify a record without providing useful information about the property itself.
For instance, an owner's phone number is unlikely to be a useful feature for predicting the value of a house.
A listing ID might also be irrelevant, especially if it is just a unique identifier.
Feature selection is the process of identifying which features should be included when training a model.
Why does this matter?
Unnecessary features can introduce noise, make a model more complicated, increase the amount of data it needs to process, and sometimes contribute to overfitting.
However, deciding which features to remove isn't always obvious.
A feature that looks unimportant on its own might become useful when combined with other features.
There are different ways to approach feature selection, including:
- Domain knowledge: using an understanding of the problem to identify relevant information.
- Statistical methods: examining relationships between features and the target.
- Model-based methods: using a model to estimate feature importance.
For now, the important distinction is this:
Feature engineering is about creating or transforming features. Feature selection is about deciding which features to use.
We'll explore more systematic ways of evaluating features as we build and assess machine learning models.
Separating features from labels
Let's assume we've inspected our dataset and decided that the information we want to use includes:
- Size.
- Bedrooms.
- Bathrooms.
- Neighbourhood.
- Property type.
Our target is the sale price.
We need to separate these two parts.
X = df.drop(columns=["sale_price"])
y = df["sale_price"]
Here:
Xcontains our input features.ycontains the labels we want the model to predict.
You may remember this notation from our earlier discussion about features and labels.
We aren't doing anything new conceptually. We're simply preparing the two parts separately so they can be used by a machine learning algorithm.
But there's one important thing we need to get right before applying our preprocessing transformations.
We need to separate the training data from the test data.
Why preprocessing must respect the train-test split
In our previous article, we established that the test set should be kept separate from the model's training process.
That principle also applies to data preprocessing.
Consider what happens when we calculate the average house size to fill missing values.
Suppose we calculate the average using every house in our dataset, including the houses reserved for testing.
We then use that average to fill missing values in the training data.
At first glance, this might seem harmless. We're only calculating an average, after all.
But we've allowed information from the test set to influence a transformation used during training.
The same problem can occur when calculating the statistics used for feature scaling, selecting features, or choosing other data-dependent transformations.
This is another form of data leakage.
The correct approach is to:
- Split the dataset into training and test sets.
- Learn preprocessing values from the training data.
- Apply the learned transformations to the training data.
- Apply those same transformations to the test data without learning anything new from it.
For example, if we use the median to fill missing property sizes, we calculate that median from the training set only.
When a missing value appears in the test set, we use the training median to fill it.
We don't calculate a new median from the test set.
The same applies to standardization: the training mean and standard deviation are used to transform both sets.
This ensures the test set remains an honest evaluation of how the model performs on information it hasn't seen during training.
A practical way to implement this
Scikit-learn provides train_test_split for separating datasets.
from sklearn.model_selection import train_test_split
X = df.drop(columns=["sale_price"])
y = df["sale_price"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
Here, 20% of the observations are reserved for testing, while 80% are used for training.
The random_state argument makes the split reproducible, meaning we can obtain the same split again when we rerun the code with the same data and settings.
Now we can prepare our preprocessing steps using the training data.
Bringing everything together with a preprocessing pipeline
So far, we've looked at different preprocessing techniques individually.
But imagine having to perform all these operations manually every time we train a model.
We would need to remember which columns require missing-value imputation, which ones need encoding, which ones need scaling, and the values calculated from the training set.
We would also need to ensure that we apply exactly the same transformations to our test data.
This can become difficult to manage.
Scikit-learn provides a useful solution: pipelines.
A pipeline allows us to combine multiple data transformations into a sequence of steps.
We can also use ColumnTransformer to apply different transformations to different columns.
Let's put together a simple example.
First, we'll identify our numerical and categorical features.
numerical_features = [
"size_sqft",
"bedrooms",
"bathrooms"
]
categorical_features = [
"neighbourhood",
"property_type"
]
Next, we'll define the transformations for each group.
For numerical features, we'll:
- Fill missing values using the median.
- Apply standardisation.
For categorical features, we'll:
- Fill missing values using the most frequent category.
- Apply one-hot encoding.
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import (
StandardScaler,
OneHotEncoder
)
numerical_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler())
])
categorical_pipeline = Pipeline([
("imputer", SimpleImputer(strategy="most_frequent")),
("encoder", OneHotEncoder(handle_unknown="ignore"))
])
Let's unpack what's happening.
The numerical pipeline first replaces missing numerical values with the median. It then standardises the resulting values.
The categorical pipeline fills missing categories using the most frequent category and then converts those categories into numerical columns.
Notice this argument:
handle_unknown="ignore"
Why do we need it?
Imagine our training data contains houses from Lekki, Ikeja, and Yaba, but the test data contains a house from a neighbourhood that wasn't present during training.
The encoder needs to handle that previously unseen category. With handle_unknown="ignore", it won't raise an error simply because the new category wasn't encountered during fitting.
Now we can combine the two pipelines.
preprocessor = ColumnTransformer([
("numerical", numerical_pipeline, numerical_features),
("categorical", categorical_pipeline, categorical_features)
])
The ColumnTransformer tells scikit-learn which transformation to apply to which columns.
Finally, we fit our preprocessing system using the training data.
X_train_prepared = preprocessor.fit_transform(X_train)
X_test_prepared = preprocessor.transform(X_test)
Pay attention to the difference between these two calls.
fit_transform() learns the necessary preprocessing information from the training data and applies the transformations.
transform() applies those already-learned transformations to the test data.
We don't call fit_transform() on the test data because we don't want it learning new preprocessing values from information reserved for evaluation.
This is an important detail.
We have now created a reusable preprocessing workflow that handles missing values, categorical encoding, and numerical scaling while keeping the training and test data separate.
As we start training machine learning models, this kind of workflow will become increasingly useful.
What have we actually achieved?
Let's step back and look at what we've done.
We started with a raw house-price dataset containing different kinds of information, potential missing values, and columns that weren't necessarily ready for a machine learning algorithm.
We explored its structure using pandas, identified possible data-quality problems, and examined some ways to handle them.
We learned how to:
- Handle missing numerical and categorical values.
- Convert categorical information into numerical representations.
- Scale numerical features.
- Create additional features through feature engineering.
- Identify features that may not be useful.
- Separate input features from target labels.
- Apply preprocessing transformations without leaking information from the test set.
Most importantly, we learned that preparing data isn't simply about making every column numerical.
It's about understanding what the data represents, deciding how to represent it appropriately, and ensuring that our preparation process doesn't compromise the way we train or evaluate a model.
A machine learning algorithm can only learn from the information we provide. If that information is poorly prepared, inconsistent, or misleading, the model's results can suffer.
This doesn't mean preprocessing guarantees a good model. It simply means we've taken an important step towards giving our model meaningful information to learn from.
What's next?
We've spent time understanding what our data looks like and how to prepare it for machine learning.
Now we're ready to do something more interesting with it.
How can a machine learn the relationship between the characteristics of a house and its selling price?
That's the question we'll explore in the next article as we introduce Linear Regression.
We'll examine how a model can learn a relationship between input features and a numerical target, and how that relationship can be used to make predictions about houses it hasn't seen before.
About the author
- I’m a software engineer with about three years of experience building backend systems and financial infrastructure at Mono. I’m also studying mathematics at Lagos State University. I use this space to document my learning, explore technical concepts, share implementations, and develop a deeper understanding of machine learning and AI research. I started a series titled Machine Learning, From Grounds Up to make complex ideas more accessible. I’m especially interested in AI safety: how neural networks generalize, what they learn internally, and how to keep capable AI models reliable. Expect posts on the basics of ML, building models from scratch, and, later, notes from reproducing research papers.
Comments
Join the discussionNo comments yet. Be the first to comment.
Machine Learning, From the Ground Up
Machine Learning can seem intimidating when you're first introduced to it. There are algorithms, models, datasets, training, predictions, neural networks, and plenty of unfamiliar terminology. But what do these things actually mean? This series breaks down machine learning from the very beginning. We'll start by understanding what it means for a machine to learn, explore how models are trained, and gradually work our way towards more advanced concepts used in modern AI.



