Menu

Data Preprocessing in Depth

Data Preprocessing in Depth

Basic cleaning is only the start. Real projects need deeper preprocessing so that data is accurate, balanced, and ready for models. This topic covers techniques that go beyond the basics and shows how to make them repeatable.

Advanced Missing Value Techniques

Simple fills like the mean or median work well in many cases, but they can hide patterns. More advanced methods use other columns to estimate missing values. For example, you can fill a missing income using the average income of similar customers.

Scikit-learn offers tools like SimpleImputer and KNNImputer for this. The KNN method looks at the closest similar rows and uses their values to fill the gap.

from sklearn.impute import KNNImputer
imputer = KNNImputer(n_neighbors=3)
df[["age", "income"]] = imputer.fit_transform(df[["age", "income"]])

You can also add a new column that marks which values were missing. Sometimes the fact that a value is missing carries useful information for the model.

Handling Outliers

Outliers are values far from the rest. They can come from errors or from real rare events. Detect them using the IQR method or Z-scores, and always plot them before deciding what to do.

If an outlier is clearly an error, fix or remove it. If it is real, think carefully before removing it, because it may hold important information. A fraud transaction is an outlier, but it may be exactly what you want to catch.

A safe middle option is capping, where you limit extreme values to a set range. Use clip() in Pandas for this. Always record what you changed and why.

Fixing Skewed Data with Transformations

Many real-world columns are skewed, meaning most values are small and a few are very large. Income and house prices are common examples. Skewed data can hurt some models.

A log transformation often reduces skew and makes the data more balanced. Other options include the square root and the Box-Cox transformation.

import numpy as np
df["income_log"] = np.log1p(df["income"])

Use log1p to handle zeros safely. Plot a histogram before and after to see the change. Remember to reverse the transformation when you report predictions in the original scale.

Building Repeatable Preprocessing Steps

Preprocessing should be repeatable. You will need to apply the exact same steps to new data later, so writing them as one-off notebook cells is risky. Put them into functions or pipelines.

Scikit-learn's Pipeline and ColumnTransformer let you combine imputing, encoding, and scaling in one object. You fit it on training data and then apply it to any new data in the same way.

This also prevents data leakage. The pipeline learns values like the mean only from the training data. This keeps your test results honest and makes your project easier to maintain.


Data Science Lifecycle Tutorial

WR

Wesline Rinisha



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details