Data Preprocessing Techniques
Data preprocessing turns source records into inputs an analysis or model can use. Common techniques include filling missing values, scaling numbers, encoding categories and selecting features. For machine learning, learn each transformation from training data and reuse it on later records.
A courier wants to predict delivery time when a parcel leaves the depot. One booking has no distance. A second travels by air, a transport mode the model has never seen. What numbers should the model receive for those two bookings?
By Shaleen Shekhar | NextGen Algorithms
On this page
Start with what was known at dispatch
A feature is an input such as route distance or transport mode. The target is the answer the model learns to predict, here the hours between dispatch and delivery. Write down the prediction time before choosing any columns. An arrival scan would reveal part of the answer. Even a perfectly scaled arrival time would still be the wrong input.
Build one row per parcel. If one parcel has three tracking scans, joining all three to its booking creates three rows for a single delivery. Select the latest scan available by dispatch, then check that each booking still appears once. For a depot lookup that should have one row per depot, a left join with validate="many_to_one" checks the lookup key. See pandas merge validation and the guide to data wrangling.
Split the resulting records to match the job. To predict future deliveries, reserve later dispatches for evaluation and make sure training outcomes were known by the cutoff. If the goal is to work in unseen depots, hold out whole depots. For independent records drawn from one stable population, a random split can be appropriate.
What does a missing or unusual value mean?
A missing distance and a distance of zero tell different stories. A blank can mean that the route service failed. A recorded zero might be valid for a handover at the depot, or it might be the system’s code for “unknown.” Check the source before changing either value.
| What you find | A reasonable first step | What can go wrong |
|---|---|---|
| Some known distances are missing | Fill with the training median as a baseline. Consider a missing-value indicator. | A single fill value hides variation. Compare errors for parcels with and without a recorded distance. |
| A field is inapplicable | Keep that meaning explicitly, such as “no return trip.” | A median return distance would describe a trip that never happened. |
| A distance of 3,000 km appears | Check route, units and source. Correct a verified unit error. Retain a genuine long route. | Deleting every long route leaves the model with little evidence about remote destinations. |
| A sensor jumps briefly | Compare nearby measurements and inspect the device. Use a trailing window if smoothing a live signal. | A centred window can use future readings that will be unavailable at prediction time. |
Mean imputation is easy to reproduce but sensitive to extremes. The median is less sensitive. For a category, a frequent-value fill can erase evidence that a value was absent. An explicit “unknown” category may be more informative. Compare options on the same validation split. See scikit-learn’s imputation guide and the NextGen guide to reading a boxplot.
How do you choose a scale or an encoding?
Changing kilometres to metres multiplies every distance by 1,000. In a nearest-neighbour model, that can make distance dominate another input measured in hours. Scaling sets a consistent numerical reference. The choice depends on how the model uses each column.
| Technique | How it works | When to consider it |
|---|---|---|
| Min-max scaling | Subtract the training minimum and divide by the training range. | Useful when a training range of 0 to 1 is convenient. A later value can fall outside that range. |
| Standardization | Subtract the training mean and divide by the training standard deviation. | A common starting point for distance-based or regularized linear models. Extreme values affect both statistics. |
| Robust scaling | Subtract the training median and divide by the interquartile range with default settings. | Consider it for a feature with valid extremes. Extreme observations remain in the data. |
| Log transformation | For a nonnegative count, log(1 + x) maps zero to zero and compresses large values. | Useful when the gap from 1 to 10 matters differently from the gap from 101 to 110. Compare validation results. |
| One-hot encoding | Create an indicator column for each known category. | Road and rail have no natural order. Integer codes could imply an ordering that a linear model would use. |
| Ordinal encoding | Map categories to a documented order, such as small, medium and large. | Use it when the order has meaning. A linear model using 1, 2 and 3 also assumes equal numerical steps. |
A constant training column has zero range and zero standard deviation. Check for it before using either formula by hand. For more examples, read feature scaling techniques and one-hot encoding vs label encoding. Implementation details appear in the preprocessing guide, RobustScaler reference and OneHotEncoder reference.
Work through one parcel by hand
Here are six fictional dispatches in time order. The first four are training records. The last two stand in for future bookings. For this example the first four delivery times were already known before the fifth parcel left.
| Parcel | Distance (km) | Mode | Actual hours | Use |
|---|---|---|---|---|
| 1 | 10 | road | 2 | Train |
| 2 | Missing | rail | 4 | Train |
| 3 | 20 | road | 4 | Train |
| 4 | 30 | rail | 6 | Train |
| 5 | 40 | air | 7 | Later |
| 6 | Missing | road | 3 | Later |
The observed training distances are 10, 20 and 30 km. Their median is 20 km, so the four training distances become 10, 20, 20 and 30. With a training minimum of 10 and maximum of 30, the scaled distance is (distance − 10) / (30 − 10).
Parcel 5 has a scaled distance of (40 − 10) / 20 = 1.5. The encoder learned two categories, rail and road. With unknown categories ignored, air gives zero in both indicator columns. The model receives [1.5, 0, 0]. Parcel 6 gets the training median, so its inputs are [0.5, 0, 1].
Fitting the scaler on all six rows would quietly change the maximum to 40. Parcel 5 would then score 1, and even parcel 4 would change from 1 to about 0.67. One future record would have changed the training data. This is data leakage. See the MinMaxScaler documentation and guide to avoiding leakage.
Try a new dispatch
Keep the training records fixed. Change a later parcel’s distance or mode to see exactly what reaches the model. Select “Distance missing” to use the 20 km training median.
40 km exceeds the training maximum. Air was absent from training.
Try 10 km by rail. The input becomes [0, 1, 0]. With a missing distance by road it becomes [0.5, 0, 1]. These two cases also give you known answers to check in your own implementation.
Build the same preprocessing pipeline in Python
This example needs Python, NumPy, pandas and scikit-learn 1.2 or later for the sparse_output argument. Run it in a notebook or a Python file. It creates all six records locally.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
# Fictional parcels in dispatch order, one row per parcel.
parcels = pd.DataFrame({
"distance_km": [10, np.nan, 20, 30, 40, np.nan],
"mode": ["road", "rail", "road", "rail", "air", "road"],
"hours": [2, 4, 4, 6, 7, 3],
})
inputs = parcels[["distance_km", "mode"]]
train, later = inputs.iloc[:4], inputs.iloc[4:]
distance = Pipeline([
("fill", SimpleImputer(strategy="median")),
("scale", MinMaxScaler()),
])
prepare = ColumnTransformer([
("distance", distance, ["distance_km"]),
("mode", OneHotEncoder(handle_unknown="ignore",
sparse_output=False), ["mode"]),
])
model = Pipeline([("prepare", prepare), ("predictor", LinearRegression())])
model.fit(train, parcels["hours"].iloc[:4])
fitted = model.named_steps["prepare"]
print(fitted.get_feature_names_out().tolist())
print(fitted.transform(later).tolist())
print(model.predict(later).round(1).tolist())What the example prints
['distance__distance_km', 'mode__mode_rail', 'mode__mode_road']
[[1.5, 0.0, 0.0], [0.5, 0.0, 1.0]]
[8.0, 4.0]The first line fixes the meaning of each number in the second. The last line gives predicted delivery times in hours. The two actual journeys took 7 and 3 hours. Four training rows are enough to check the transformations, but far too few to judge how well this model predicts real deliveries.
ColumnTransformer applies a different recipe to each column. Pipeline keeps those recipes with the fitted predictor, so a new booking goes through the same steps. For a wider table, keep one-hot output sparse if your model supports it. A dense indicator matrix can become large when a column has thousands of categories. See scikit-learn’s mixed-column example.
When does reducing the data help?
Start with a simple question: what information would you lose? A booking reference can help join two tables, but a unique ID has little use as a numerical measure of journey time. Keep it for tracing predictions and leave it out of the model inputs.
Feature selection
Keep a subset of the original columns. If you use the target to rank features, repeat the selection inside each training fold. Selecting on the full dataset gives the test targets a say.
Aggregation
Turn earlier scans into a count or elapsed time. Fix the cutoff at dispatch. An average that includes scans made during delivery can reveal the journey you are trying to predict.
Dimensionality reduction
Principal component analysis (PCA) combines numerical inputs into new directions that capture variance. The results are harder to explain in the original units. Fit PCA on training data and decide whether the inputs need scaling first.
If you need to explain why a prediction changed, retaining named features may help. Read feature selection methods for selection strategies and the PCA reference for how scikit-learn centres inputs.
When should a number become a band?
Discretization puts continuous values into bins. Suppose a courier charges local rates below 10 km, regional rates from 10 km to below 30 km, and long-distance rates from 30 km upward. These fixed business boundaries put 10 km in the regional band and 30 km in the long-distance band. Write down where the endpoints belong.
Binning loses detail: 11 km and 29 km now have the same label. Keep the original distance if the model needs that difference. If you learn bins from quantiles, find the boundaries on training data and reuse them later. KBinsDiscretizer supports uniform-width, quantile and k-means strategies.
How should you sample and validate records?
Random sampling can be useful when bookings are independent. Stratified sampling preserves approximate shares of a chosen class, such as late deliveries. Sampling entire depots is cluster sampling: every selected depot can contribute many similar bookings. Check whether the depots and routes in the sample match the population you want to serve.
For a late-delivery classifier, a team might oversample late deliveries while training. Split first and resample only the training part of each fold. Keep evaluation data at the class mix expected in use so the test answers the operational question. See the imbalanced-learn resampling example.
Pick folds that match the prediction task
A fold is one part of a dataset held out for validation while the model trains on other parts. For future dispatches, train on earlier blocks and validate on later ones. For unseen depots, use group-aware folds. Fit the whole pipeline separately in each fold. See scikit-learn’s cross-validation guide.
What should you check before using the pipeline?
| Check | Quick test | What a failure tells you |
|---|---|---|
| Input contract | Require distance in kilometres and a dispatch-time mode. Verify one booking per row. | A schema or unit change can produce plausible but wrong predictions. |
| Cutoff and label timing | Trace one training row back to the timestamps of every input and its target. | A late-arriving field or overlapping outcome window can leak information. |
| Expected transformations | Run the 40 km air parcel and the missing-distance road parcel through the saved pipeline. | A changed median, category order or scale will alter the expected arrays. |
| Missing and unfamiliar inputs | Count missing distances, unseen modes and observations outside the training range by depot. | A new carrier or a failed route service may need its own handling. |
| Predictive accuracy | Compare validation errors in hours with a baseline that always predicts the training median delivery time. | Extra complexity may add little. Check routes separately so a frequent route cannot hide large errors elsewhere. |
Data validation and model validation answer different questions. A range check can catch a distance of minus five kilometres. Cross-validation estimates how the fitted pipeline performs on held-out records. Passing one check tells you little about the other.
Practice with another dataset
- Chipotle orders (TSV). Count items per order. Check the unit of a row before removing repeated order IDs.
- Heights and weights (CSV). Inspect the header, confirm inches and pounds, then convert units before comparing distributions.
- Adult dataset, UCI repository. Inspect the attribute descriptions and missing-value conventions before choosing an encoder.
- Titanic dataset, OpenML. For an exercise predicting survival at boarding time, identify columns that record what happened later.
Check your understanding
Choose one answer per question. You can also open each explanation directly.
A later parcel is missing its distance. Which value does this pipeline use?
Answer and explanation
The training median of 20 km. The imputer learned 20 km from the observed training distances. Later bookings reuse that value.
A 50 km parcel arrives. What does the fitted scaler return?
Answer and explanation
2. (50 − 10) / (30 − 10) = 2. The scaler in this example uses its default setting with clipping off.
A booking is due to travel by air. What are its rail and road indicators?
Answer and explanation
0 and 0. The encoder learned rail and road. With unknown categories ignored, an unseen mode sets both indicators to zero.
Which field is available for a prediction at dispatch?
Answer and explanation
Distance estimated when booked. The booking estimate exists at dispatch. The other two fields depend on events later in the trip.
How would you test a model intended for previously unseen depots?
Answer and explanation
Reserve whole depots for validation. Holding out a depot measures how the fitted pipeline handles a group it did not see during training.
Where should target-based feature selection run?
Answer and explanation
Inside each training fold. Selecting features with validation or test targets leaks information into the model-building process.
Score: 0 / 0 answered
Frequently asked questions
What is the difference between data cleaning and preprocessing?
Cleaning corrects or flags problems in the records. Preprocessing also includes changes a model needs, such as converting a valid text category into numerical features. A clean table can still need preprocessing.
Should I split the data before filling missing values?
Yes, when the fill value comes from the data. Compute the median or other estimate on training rows, then reuse it on validation and test rows. A fixed rule such as converting metres to kilometres can be applied consistently to every split.
Is normalization the same as standardization?
Standardization subtracts a feature mean and divides by its standard deviation. Min-max scaling uses the feature range. Some tutorials call min-max scaling normalization, while scikit-learn’s Normalizer rescales each sample to unit norm. Check which operation a tutorial means.
Why did a scaled test value come out above 1?
With the default min-max settings, a value above the training maximum maps above 1. If 10 to 30 km mapped to 0 to 1 during training, 40 km maps to 1.5. Check the units and the new data before deciding whether to clip.
What should I do with a category the model has never seen?
Decide how the encoder should represent it. OneHotEncoder with handle_unknown="ignore" leaves that field’s indicator columns at zero. Track how often this happens, since the model has no category-specific training examples for the new value.
Do decision trees need feature scaling?
Ordinary decision trees split a numerical feature at a threshold. A simple change of units preserves the order of observations, so scaling is usually unnecessary for that split. Missing-value and categorical support still depend on the estimator.
How can I tell whether a preprocessing change helped?
Compare two complete pipelines on the same validation folds, using the same model and metric. Fit each transformation inside its training fold. Use the untouched test set once you have chosen the approach.
References and further reading
- scikit-learn | Common pitfalls and recommended practices
- scikit-learn | Preprocessing data
- scikit-learn | Imputation of missing values
- scikit-learn | Column Transformer with Mixed Types
- scikit-learn | Cross-validation: evaluating estimator performance
- scikit-learn | OneHotEncoder
- scikit-learn | MinMaxScaler
- scikit-learn | RobustScaler
- scikit-learn | KBinsDiscretizer
- scikit-learn | Principal component analysis
- pandas | pandas.merge
- imbalanced-learn | Common pitfalls when resampling
Post a Comment