Skip to content
Machine Learning

Data Preprocessing

Scale, encode, and impute features with sklearn.

By EZ4Code Team
preprocessingscalingencoding

Code

import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

X = np.array([[1, 2], [3, np.nan], [5, 6], [7, 8]])

# Impute missing values
imputer = SimpleImputer(strategy="mean")
X_imp = imputer.fit_transform(X)

# Standardize (zero mean, unit variance)
scaler = StandardScaler()
X_std = scaler.fit_transform(X_imp)

# Scale to [0, 1]
minmax = MinMaxScaler()
X_mm = minmax.fit_transform(X_imp)

# One-hot encode categorical features
enc = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
X_cat = enc.fit_transform([["red"], ["green"], ["blue"], ["red"]])
print(X_std, X_cat)

Explanation

Preprocessing transformers convert raw data into a numeric matrix suitable for models. StandardScaler centers and scales to unit variance, MinMaxScaler maps to a fixed range, and SimpleImputer fills missing values with a statistic. OneHotEncoder expands categorical columns into binary indicator columns.

More Machine Learning Snippets