Data Preprocessing: Missing Values, Outliers & Encoding

In real-world machine learning, raw datasets are rarely clean.

Sensor systems may fail to record readings, customers may leave optional form fields blank, financial datasets may contain extreme transactions, and categorical information may be stored as text rather than numerical values.

Machine learning algorithms generally require properly structured numerical inputs. Therefore, raw data must be examined, cleaned, transformed, and prepared before model training.

This process is called Data Preprocessing.

Three foundational preprocessing tasks are:

  1. Handling Missing Values: Identifying and treating incomplete observations.
  2. Managing Outliers: Detecting and appropriately handling unusually extreme values.
  3. Categorical Encoding: Converting categorical variables into numerical representations.

In this guide, we will understand these techniques, explore their mathematical foundations, and implement them using Python, Pandas, and Scikit-learn.


1. Handling Missing Values

Missing values occur when information is unavailable for one or more observations in a dataset.

They are commonly represented as:

  • NaN in Pandas.
  • None in Python.
  • NULL in databases.
  • Empty or blank fields in CSV files.

Consider the following dataset:

CustomerAgeSalaryCity
A2530000Delhi
B30NaNMumbai
CNaN45000Bangalore
D3550000NaN
E4055000Delhi

The dataset contains missing values in three columns.

Before deciding how to handle them, it is important to understand why the values are missing.

1.1 Types of Missing Data

There are three major statistical mechanisms describing missingness.

A. MCAR (Missing Completely at Random)

A value is MCAR when its probability of being missing is unrelated to both observed and unobserved data.

Example:

A temperature sensor randomly fails to transmit readings because of a temporary network interruption.

The missing readings are unrelated to the actual temperature or any other measured variable.

Possible solutions:

  • Row deletion when the amount of missing data is small and deletion is appropriate.
  • Mean or median imputation.
  • Other simple imputation techniques.

Even under MCAR, deletion reduces sample size and may increase uncertainty.

B. MAR (Missing at Random)

A value is MAR when its probability of being missing depends on other observed variables, rather than the missing value itself after accounting for those observed variables.

Example:

Younger survey respondents are more likely to skip the income question.

The probability of income being missing depends on the observed age variable.

Possible solutions:

  • Multivariate imputation.
  • KNN imputation.
  • Iterative imputation.
  • Group-based imputation when justified.

These approaches can use relationships among observed features to estimate missing values.

C. MNAR (Missing Not at Random)

A value is MNAR when its probability of being missing depends on the missing value itself or on unobserved information related to it.

Example:

Applicants with particularly high debt may be less likely to disclose their debt information.

The missingness may depend on the actual debt amount.

Possible solutions:

  • Missingness indicator variables.
  • Domain-specific investigation.
  • Sensitivity analysis.
  • Statistical models that explicitly account for the missingness mechanism.

A missingness indicator can capture useful information, but it does not automatically solve MNAR bias. In some cases, additional assumptions or external information are necessary.

Comparison of Missing Data Mechanisms

TypeMissingness Depends OnExample
MCARNeither observed nor unobserved dataRandom network failure
MAROther observed variablesIncome missing more frequently among younger respondents
MNARThe missing value itself or unobserved informationHigh-debt applicants withholding debt information

1.2 Detecting Missing Values Using Pandas

Pandas provides several useful methods for identifying missing values.

import pandas as pd
import numpy as np

data = {
    "Age": [25, 30, np.nan, 35, 40],
    "Salary": [30000, np.nan, 45000, 50000, 55000],
    "City": ["Delhi", "Mumbai", "Bangalore", np.nan, "Delhi"]
}

df = pd.DataFrame(data)

# Display the dataset
print(df)

# Count missing values in each column
print(df.isnull().sum())

# Calculate missing percentage
missing_percentage = (
    df.isnull().mean() * 100
)

print(missing_percentage)

# Total missing values
print("Total missing values:", df.isnull().sum().sum())

Useful methods:

MethodPurpose
isnull()Identifies missing values
notnull()Identifies available values
isnull().sum()Counts missing values
isnull().mean()Calculates missing proportions
dropna()Removes rows or columns with missing values
fillna()Replaces missing values

1.3 Common Missing Value Treatment Strategies

A. Row Deletion

Remove observations containing missing values.

df_clean = df.dropna()

Useful when:

  • Missing values are relatively rare.
  • Removing observations does not introduce meaningful bias.
  • Enough representative data remains.

Limitation: You lose potentially valuable observations.

B. Column Deletion

Remove a feature when too much information is missing and the feature is not sufficiently useful.

df_clean = df.drop(
    columns=["City"]
)

There is no universal percentage threshold for deleting a column. A feature with 60% missing values may still be important, depending on the problem and missingness mechanism.

C. Mean Imputation

Replace missing numerical values with the column's mean.

\[ \text{Mean}=\frac{\sum_{i=1}^{n}x_i}{n} \]

df["Salary"] = df["Salary"].fillna(
    df["Salary"].mean()
)

Best suited for numerical features with relatively symmetric distributions and limited extreme values.

D. Median Imputation

Replace missing values with the middle value after sorting the observations.

\[ \text{Median}=\text{Middle value of sorted observations} \]

df["Age"] = df["Age"].fillna(
    df["Age"].median()
)

Median imputation is often preferred when numerical data is skewed or contains extreme observations.

E. Mode Imputation

Replace missing categorical values with the most frequently occurring category.

df["City"] = df["City"].fillna(
    df["City"].mode()[0]
)

This is useful when a categorical feature has a meaningful dominant category.

However, it can increase the apparent frequency of that category.

F. KNN Imputation

K-Nearest Neighbors imputation estimates missing values using observations that are similar across other available features.

For example, if a customer's age is missing, KNN can use nearby customers with similar salary and other relevant characteristics to estimate it.

from sklearn.impute import KNNImputer

imputer = KNNImputer(
    n_neighbors=3
)

numeric_data = df[
    ["Age", "Salary"]
]

imputed_data = imputer.fit_transform(
    numeric_data
)

print(imputed_data)

Advantages:

  • Uses relationships between observations.
  • Can preserve more complex patterns than simple mean imputation.

Limitations:

  • Computationally more expensive.
  • Sensitive to feature scaling.
  • Can perform poorly when the chosen features do not represent meaningful similarity.

G. Iterative Imputation

Iterative imputation estimates missing values by modeling each incomplete feature using the other available features.

It repeatedly updates estimates until the process reaches its stopping condition.

from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer

imputer = IterativeImputer(
    max_iter=10,
    random_state=42
)

imputed_data = imputer.fit_transform(
    numeric_data
)

print(imputed_data)

This approach can capture relationships among multiple variables, but its quality depends on the modeling assumptions and data structure.

1.4 Missingness Indicator

Sometimes, the fact that a value is missing is itself informative.

We can create an additional binary feature:

\[ \text{is\_missing}= \begin{cases} 1 & \text{If the value is missing}\\ 0 & \text{Otherwise} \end{cases} \]

Python implementation:

df["Salary_missing"] = (
    df["Salary"].isnull().astype(int)
)

The model can then use both the imputed salary and the missingness indicator.

This can be useful under different missingness mechanisms, especially when missingness has predictive information.


2. Detecting and Managing Outliers

An outlier is an observation that differs substantially from the general pattern of a dataset.

Outliers can occur because of:

  • Data entry errors.
  • Faulty sensors.
  • Measurement errors.
  • Rare but genuine events.
  • Unusual customer behavior.
  • Fraudulent transactions.

Consider the following salaries:

25000, 28000, 30000, 32000, 35000, 38000, 500000

Most values lie between ₹25,000 and ₹38,000.

However, ₹500,000 is substantially higher than the other observations.

It may be an outlier, but that does not necessarily mean it is incorrect.

An executive salary, for example, could legitimately be much higher than the rest of the dataset.

Important: Outlier detection and outlier treatment are different processes. Detecting an unusual value does not automatically justify removing it.

2.1 Z-Score Method

The Z-score measures how many standard deviations an observation is from the mean.

\[ Z=\frac{x-\mu}{\sigma} \]

Where:

  • \(x\): Observed value.
  • \(\mu\): Mean.
  • \(\sigma\): Standard deviation.

A common screening rule is:

\[ |Z|>3 \]

Values beyond this threshold are flagged for investigation.

Example:

Suppose:

\[ \mu=50,\quad \sigma=10 \]

For an observation:

\[ x=85 \]

Then:

\[ Z=\frac{85-50}{10}=3.5 \]

Since:

\[ |3.5|>3 \]

The observation is flagged as a potential outlier.

Python implementation:

import numpy as np
from scipy.stats import zscore

values = np.array([
    25, 28, 30, 32, 35, 38, 100
])

z_scores = zscore(values)

outliers = values[
    np.abs(z_scores) > 3
]

print("Z-Scores:", z_scores)
print("Potential outliers:", outliers)

Limitation: The traditional Z-score is sensitive to extreme values because both the mean and standard deviation can be affected by outliers. It is most useful as a screening technique for approximately symmetric, bell-shaped distributions.

2.2 IQR (Interquartile Range) Method

The Interquartile Range method is a robust approach for identifying potential outliers.

It uses the middle 50% of observations rather than relying on the mean and standard deviation.

\[ IQR=Q_3-Q_1 \]

Where:

  • \(Q_1\): 25th percentile.
  • \(Q_3\): 75th percentile.

The conventional lower and upper fences are:

\[ \text{Lower Bound}=Q_1-1.5(IQR) \]

\[ \text{Upper Bound}=Q_3+1.5(IQR) \]

Observations outside these bounds are flagged as potential outliers.

Example:

Suppose:

\[ Q_1=20,\quad Q_3=40 \]

Then:

\[ IQR=40-20=20 \]

Lower bound:

\[ 20-1.5(20)=-10 \]

Upper bound:

\[ 40+1.5(20)=70 \]

Any observation below -10 or above 70 is flagged.

Python implementation:

import pandas as pd

data = pd.Series([
    25, 28, 30, 32, 35, 38, 100
])

Q1 = data.quantile(0.25)
Q3 = data.quantile(0.75)

IQR = Q3 - Q1

lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

outliers = data[
    (data < lower_bound) |
    (data > upper_bound)
]

print("Q1:", Q1)
print("Q3:", Q3)
print("IQR:", IQR)

print("Lower Bound:", lower_bound)
print("Upper Bound:", upper_bound)

print("Outliers:")
print(outliers)

2.3 Visual Outlier Detection

Visualizations help understand the distribution and identify unusual observations.

Box Plot

A box plot displays:

  • Median.
  • First quartile.
  • Third quartile.
  • Interquartile range.
  • Potential outlier observations.
import matplotlib.pyplot as plt
import seaborn as sns

data = [25, 28, 30, 32, 35, 38, 100]

sns.boxplot(x=data)

plt.title("Outlier Detection Using Box Plot")
plt.xlabel("Values")

plt.show()

Histogram

A histogram helps identify skewness, long tails, multiple peaks, and unusual distribution patterns.

sns.histplot(
    data,
    bins=10,
    kde=True
)

plt.title("Distribution of Data")
plt.xlabel("Values")
plt.ylabel("Frequency")

plt.show()

2.4 Model-Based Outlier Detection

For more complex datasets, especially when multiple features interact, statistical methods based on individual columns may not be sufficient.

Model-based techniques can identify unusual combinations of feature values.

A. Isolation Forest

Isolation Forest identifies observations that are easier to isolate from the rest of the dataset.

The intuition is that unusual observations generally require fewer random partitioning steps to isolate.

from sklearn.ensemble import IsolationForest
import numpy as np

X = np.array([
    [25, 30000],
    [30, 35000],
    [35, 40000],
    [40, 45000],
    [45, 50000],
    [90, 500000]
])

model = IsolationForest(
    contamination=0.1,
    random_state=42
)

predictions = model.fit_predict(X)

print(predictions)

The output is:

  • 1: Normal observation.
  • -1: Potential anomaly.

The contamination parameter influences the expected proportion of outliers and should be selected carefully.

B. DBSCAN

DBSCAN is a density-based clustering algorithm.

It groups observations in dense regions and identifies points that do not belong to sufficiently dense clusters as noise.

It is useful when anomalies can be identified through local density patterns.

However, DBSCAN is sensitive to parameter selection and feature scaling.


3. Outlier Treatment Strategies

After detecting potential outliers, decide how to handle them based on the domain and modeling objective.

A. Removing Outliers

Remove observations only when there is strong evidence that they are invalid, corrupted, or outside the possible range.

df_clean = df[
    (df["Salary"] >= 0) &
    (df["Salary"] <= 200000)
]

The limits in this example are illustrative. Real-world limits should come from domain knowledge or justified data-quality rules.

Risk: Removing genuine rare observations can introduce bias and eliminate important information.

B. Winsorization (Capping)

Winsorization replaces extreme values with selected percentile boundaries instead of removing observations.

For example:

  • Values below the 1st percentile are replaced by the 1st percentile.
  • Values above the 99th percentile are replaced by the 99th percentile.
lower = df["Salary"].quantile(0.01)
upper = df["Salary"].quantile(0.99)

df["Salary_capped"] = (
    df["Salary"].clip(
        lower=lower,
        upper=upper
    )
)

This preserves the number of observations while reducing the influence of extreme values.

The percentile thresholds must be estimated using training data only.

C. Log Transformation

A logarithmic transformation compresses large positive values.

A common transformation is:

\[ x'=\log(1+x) \]

This is useful for nonnegative features with strongly right-skewed distributions.

import numpy as np

df["Salary_log"] = np.log1p(
    df["Salary"]
)

The transformation reduces the distance between large values, but it does not remove invalid observations or automatically make every distribution normal.

D. Robust Scaling

Robust scaling uses the median and interquartile range rather than the mean and standard deviation.

\[ X'=\frac{X-\text{Median}(X)}{IQR(X)} \]

from sklearn.preprocessing import RobustScaler

scaler = RobustScaler()

scaled_data = scaler.fit_transform(
    df[["Salary"]]
)

print(scaled_data)

This is useful when numerical features contain extreme values and the chosen algorithm is sensitive to feature scales.

E. Using Tree-Based Models

Decision Trees, Random Forests, and Gradient Boosting models are often less sensitive to the scale of numerical features than distance-based algorithms.

They generally split on feature thresholds rather than relying on Euclidean distances.

However, they are not completely immune to outliers.

Extreme values can still influence:

  • Split selection.
  • Leaf predictions.
  • Regression error.
  • Model performance on rare observations.

4. Categorical Encoding: Converting Text into Numbers

Most machine learning algorithms operate on numerical representations.

However, real-world datasets frequently contain categorical information.

Examples include:

  • Gender.
  • City.
  • Department.
  • Product category.
  • Education level.
  • Customer membership type.

Categorical encoding converts these values into numerical representations suitable for machine learning algorithms.

There are two important types of categorical variables.

4.1 Nominal Variables

Nominal variables represent categories without a natural order.

Examples:

  • Red, Blue, Green.
  • Delhi, Mumbai, Bangalore.
  • Laptop, Mobile, Tablet.

Assigning arbitrary numerical values such as 1, 2, and 3 can introduce a false sense of order.

For example:

Delhi = 1
Mumbai = 2
Bangalore = 3

A model may incorrectly interpret Bangalore as greater than Mumbai.

One-hot encoding is commonly used for nominal variables.

4.2 Ordinal Variables

Ordinal variables represent categories with a meaningful order.

Examples:

Low < Medium < High

Other examples:

  • Beginner, Intermediate, Advanced.
  • Bronze, Silver, Gold.
  • Poor, Average, Good, Excellent.

Ordinal encoding is appropriate when the category ordering is meaningful.

Nominal vs. Ordinal Encoding

FeatureNominalOrdinal
Natural orderNoYes
ExampleCityEducation level
Common encodingOne-HotOrdinal
Numerical relationshipNo inherent rankingMeaningful ranking

5. Common Categorical Encoding Techniques

A. Label Encoding

Label encoding assigns a unique integer to each category.

Example:

Red   → 0
Blue  → 1
Green → 2

Python implementation:

from sklearn.preprocessing import LabelEncoder

data = [
    "Red",
    "Blue",
    "Green",
    "Red",
    "Blue"
]

encoder = LabelEncoder()

encoded_data = encoder.fit_transform(data)

print(encoded_data)

Output:

[2 0 1 2 0]

The exact assigned numbers depend on the encoder's category ordering.

Best suited for:

  • Target labels in classification.
  • Certain algorithms and workflows where integer category codes are explicitly treated as categories.

Important: Applying arbitrary integer labels to nominal input features can create misleading numerical relationships, especially for linear models and distance-based algorithms.

B. One-Hot Encoding

One-hot encoding creates a separate binary feature for each category.

Example:

Original feature:

Color
-----
Red
Blue
Green
Red

After one-hot encoding:

RedBlueGreen
100
010
001
100

Python implementation:

import pandas as pd

data = pd.DataFrame({
    "Color": [
        "Red",
        "Blue",
        "Green",
        "Red"
    ]
})

encoded_data = pd.get_dummies(
    data,
    columns=["Color"],
    dtype=int
)

print(encoded_data)

Scikit-learn implementation:

from sklearn.preprocessing import OneHotEncoder

encoder = OneHotEncoder(
    handle_unknown="ignore",
    sparse_output=False
)

encoded_data = encoder.fit_transform(
    data[["Color"]]
)

print(encoded_data)

Advantages:

  • Does not impose an artificial ranking.
  • Suitable for nominal categories.
  • Works well with many linear and distance-based algorithms.

Limitations:

  • Increases the number of features.
  • Can create high-dimensional datasets when categories are numerous.
  • May require careful handling of unseen categories.

For binary features, dropping one category can avoid perfect multicollinearity in some linear-model setups. However, this is not always necessary, and it is generally unnecessary for tree-based models.

C. Ordinal Encoding

Ordinal encoding converts ordered categories into integer values.

Example:

Low    → 0
Medium → 1
High   → 2

Python implementation:

from sklearn.preprocessing import OrdinalEncoder

data = [
    ["Low"],
    ["Medium"],
    ["High"],
    ["Low"]
]

encoder = OrdinalEncoder(
    categories=[["Low", "Medium", "High"]]
)

encoded_data = encoder.fit_transform(data)

print(encoded_data)

Advantages:

  • Uses fewer features than one-hot encoding.
  • Preserves meaningful category ordering.
  • Useful for genuinely ordered variables.

Limitation: The numerical distances between categories should not automatically be interpreted as equal or meaningful. For example, the difference between Low and Medium may not be equivalent to the difference between Medium and High.

D. Frequency Encoding

Frequency encoding replaces each category with its frequency or proportion in the training data.

Example:

Delhi      → 0.50
Mumbai     → 0.30
Bangalore  → 0.20

Python implementation:

import pandas as pd

df = pd.DataFrame({
    "City": [
        "Delhi",
        "Delhi",
        "Mumbai",
        "Bangalore",
        "Mumbai"
    ]
})

frequency = df["City"].value_counts(
    normalize=True
)

df["City_encoded"] = (
    df["City"].map(frequency)
)

print(df)

Advantages:

  • Creates one numerical feature instead of many.
  • Useful for high-cardinality categorical variables.
  • Relatively simple to implement.

Limitations:

  • Different categories can have identical frequencies.
  • Category identity is partially lost.
  • Frequency alone may not represent the category's relationship with the target.

For predictive workflows, frequencies must be learned from training data and then applied to validation and test data.

E. Target Encoding

Target encoding replaces each category with a statistic calculated from the target variable, commonly its mean for regression or binary classification.

Example:

Suppose we want to predict whether a customer will purchase a product.

CityPurchase
Delhi1
Delhi1
Mumbai0
Mumbai1
Bangalore0

The average purchase rate is:

Delhi     → 1.00
Mumbai    → 0.50
Bangalore → 0.00

Python implementation:

import pandas as pd

df = pd.DataFrame({
    "City": [
        "Delhi",
        "Delhi",
        "Mumbai",
        "Mumbai",
        "Bangalore"
    ],
    "Purchase": [1, 1, 0, 1, 0]
})

target_mean = df.groupby(
    "City"
)["Purchase"].mean()

df["City_encoded"] = (
    df["City"].map(target_mean)
)

print(df)

Important: This simple example illustrates the calculation, not a safe production training workflow.

Calculating category means using the same target labels that the model will train on can cause target leakage and overfitting.

For reliable model training:

  • Use out-of-fold target encoding for training observations.
  • Use mappings learned from the training data for validation and test data.
  • Apply smoothing for categories with very few observations.
  • Handle unseen categories using a global mean or another defined fallback.

A smoothed target encoding can be expressed as:

\[ TE(c)= \frac{n_c\bar{y}_c+m\bar{y}} {n_c+m} \]

Where:

  • \(n_c\): Number of observations in category \(c\).
  • \(\bar{y}_c\): Mean target value for category \(c\).
  • \(\bar{y}\): Overall target mean.
  • \(m\): Smoothing parameter.

Smoothing reduces the influence of unreliable estimates from rare categories.

F. Binary Encoding

Binary encoding converts category identifiers into binary representations.

For example:

Category A → 001
Category B → 010
Category C → 011
Category D → 100

It can reduce the number of generated features compared with one-hot encoding when the number of categories is large.

It is generally implemented using specialized libraries such as category_encoders.


6. Comparing Categorical Encoding Methods

Encoding MethodBest Use CaseMain AdvantageMain Limitation
Label EncodingTarget labels or categorical-aware workflowsSimple integer representationCan imply false order
One-Hot EncodingLow-cardinality nominal variablesNo artificial rankingMore features
Ordinal EncodingOrdered categoriesPreserves category orderImplies numerical spacing
Frequency EncodingHigh-cardinality featuresCompact representationLoses category identity
Target EncodingHigh-cardinality predictive featuresCaptures target relationshipLeakage risk
Binary EncodingHigh-cardinality featuresFewer columns than one-hotMore complex interpretation

The best encoding method depends on the feature, algorithm, dataset size, and number of unique categories.


7. Complete Data Preprocessing Using Scikit-Learn Pipelines

In practical machine learning projects, preprocessing should be part of a reproducible pipeline.

A pipeline helps ensure that the same transformations are applied consistently during training, validation, and inference.

It also reduces the risk of data leakage.

Let's build a preprocessing pipeline for numerical and categorical features.

Step 1: Import Libraries

import pandas as pd
import numpy as np

from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

from sklearn.impute import SimpleImputer
from sklearn.preprocessing import (
    StandardScaler,
    OneHotEncoder
)

from sklearn.ensemble import RandomForestClassifier

Step 2: Create a Sample Dataset

df = pd.DataFrame({
    "Age": [
        25, 30, np.nan, 35, 40,
        28, 45, 50, 32, 38
    ],

    "Salary": [
        30000, 40000, 45000, np.nan,
        55000, 35000, 60000, 65000,
        42000, 500000
    ],

    "City": [
        "Delhi", "Mumbai", "Delhi",
        "Bangalore", "Mumbai", "Delhi",
        "Bangalore", np.nan, "Mumbai",
        "Delhi"
    ],

    "Purchased": [
        0, 1, 0, 1, 1,
        0, 1, 1, 0, 1
    ]
})

Step 3: Separate Features and Target

X = df.drop(
    columns=["Purchased"]
)

y = df["Purchased"]

Step 4: Split the Dataset

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42,
    stratify=y
)

For a real project, keep a separate validation set or use cross-validation for model selection. This small dataset is only for demonstrating the preprocessing structure.

Step 5: Identify Numerical and Categorical Features

numeric_features = [
    "Age",
    "Salary"
]

categorical_features = [
    "City"
]

Step 6: Build Numerical Preprocessing

numeric_transformer = Pipeline(
    steps=[
        (
            "imputer",
            SimpleImputer(strategy="median")
        ),
        (
            "scaler",
            StandardScaler()
        )
    ]
)

This pipeline:

  1. Replaces missing numerical values with the training median.
  2. Standardizes the numerical features.

Step 7: Build Categorical Preprocessing

categorical_transformer = Pipeline(
    steps=[
        (
            "imputer",
            SimpleImputer(strategy="most_frequent")
        ),
        (
            "encoder",
            OneHotEncoder(handle_unknown="ignore")
        )
    ]
)

This pipeline:

  1. Replaces missing categorical values with the most frequent training category.
  2. Converts categorical values into one-hot encoded features.
  3. Handles previously unseen categories without raising an error.

Step 8: Combine Both Pipelines

preprocessor = ColumnTransformer(
    transformers=[
        (
            "num",
            numeric_transformer,
            numeric_features
        ),
        (
            "cat",
            categorical_transformer,
            categorical_features
        )
    ]
)

Step 9: Add a Machine Learning Model

model = Pipeline(
    steps=[
        ("preprocessor", preprocessor),

        (
            "classifier",
            RandomForestClassifier(
                n_estimators=100,
                random_state=42
            )
        )
    ]
)

Step 10: Train and Evaluate

model.fit(
    X_train,
    y_train
)

accuracy = model.score(
    X_test,
    y_test
)

print(
    f"Test Accuracy: {accuracy:.2%}"
)

The complete pipeline ensures that:

  • Imputation statistics are learned from training data.
  • Scaling parameters are learned from training data.
  • One-hot categories are learned from training data.
  • The same fitted transformations are applied to test data.

Important: This example does not implement a specific outlier treatment step. Outlier handling should be added when justified by the dataset and domain. If you add a custom capping or transformation step, its thresholds must also be learned only from the training data.


8. Data Leakage: The Most Important Preprocessing Mistake

Data leakage occurs when information that should not be available during model training influences the training process.

Preprocessing can unintentionally introduce leakage.

Consider this incorrect workflow:

# Incorrect approach

scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(
    X_scaled,
    y,
    test_size=0.2,
    random_state=42
)

Here, the scaler learns the mean and standard deviation using the entire dataset, including the test observations.

This allows information from the test set to influence the training transformations.

A safer workflow is:

# Correct approach

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42
)

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(
    X_train
)

X_test_scaled = scaler.transform(
    X_test
)

Notice the difference:

  • fit_transform() learns and applies transformations to training data.
  • transform() applies the already learned transformations to test data.

The same rule applies to:

  • Mean and median imputation.
  • Scaling.
  • Feature selection.
  • Outlier thresholds.
  • Frequency encoding.
  • Target encoding.
  • Dimensionality reduction.

For cross-validation, fit all learned preprocessing steps independently within each training fold. Scikit-learn pipelines help automate this process.


9. Best Practices for Real-World Data Preprocessing

Before training a machine learning model, follow a systematic process.

Missing Values

  • Inspect missing-value counts and percentages.
  • Understand why values are missing.
  • Choose deletion or imputation based on the problem.
  • Consider missingness indicators.
  • Fit imputers using training data only.

Outliers

  • Investigate whether extreme values are errors or genuine observations.
  • Use domain knowledge before removing data.
  • Compare Z-score and IQR approaches where appropriate.
  • Consider transformations or capping.
  • Evaluate how outlier treatment affects model performance.

Categorical Encoding

  • Identify nominal and ordinal variables.
  • Use one-hot encoding for suitable nominal features.
  • Use ordinal encoding only when ordering is meaningful.
  • Consider frequency, binary, or target encoding for high-cardinality features.
  • Handle previously unseen categories.
  • Prevent target leakage when using target encoding.

General Preprocessing

  • Separate features and target before modeling.
  • Split data before fitting preprocessing transformations.
  • Use pipelines for reproducibility.
  • Preserve an untouched test dataset.
  • Compare model performance before and after preprocessing.
  • Document every transformation.

10. Conclusion

Data preprocessing is one of the most important stages of a machine learning project.

A model cannot reliably learn useful patterns when its input data contains unresolved missing values, misleading extreme observations, or incorrectly represented categorical features.

The three foundational techniques covered in this guide are:

  1. Missing Value Handling: Uses deletion, imputation, or missingness indicators to manage incomplete information.
  2. Outlier Detection and Treatment: Uses statistical, visual, and model-based methods to investigate and manage extreme observations.
  3. Categorical Encoding: Converts nominal and ordinal features into appropriate numerical representations.

The most important lesson is that preprocessing should not be performed blindly. Every transformation should be justified by the data, the business problem, and the machine learning algorithm.

Remember: A successful machine learning model does not begin with an algorithm. It begins with understanding and preparing the data correctly.