Preprocessing and feature engineering
Preprocessing turns raw columns into numbers a model can use, with parameters learned from the training rows only. This page covers scalers, encoders, imputers, binning, polynomial and date features, transforms for skewed values, feature selection and the rules that keep test data out of training. The examples use data/houses.csv and data/customers.csv. The blocks share one session:
import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_split
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
houses = pd.read_csv("data/houses.csv")customers = pd.read_csv("data/customers.csv")h_train, h_test = train_test_split(houses, test_size=0.25, random_state=42)c_train, c_test = train_test_split( customers, test_size=0.25, stratify=customers["churned"], random_state=42)Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| mean 0, standard deviation 1 | StandardScaler() |
linear models, SVM, KNN, PCA, neural nets |
| a fixed range such as 0–1 | MinMaxScaler(feature_range=(0, 1), clip=True) |
bounded inputs, images |
| scaling that ignores outliers | RobustScaler() |
median and IQR |
| scale sparse data | MaxAbsScaler() |
keeps zeros |
| make a skewed column look normal | PowerTransformer() (Yeo-Johnson) |
method="box-cox" for positive data |
| ranks to a uniform or normal shape | QuantileTransformer(output_distribution="normal") |
robust to outliers; non-linear |
| tame a right tail by hand | np.log1p(x); undo with np.expm1 |
counts, prices, durations |
| scale each row to length 1 | Normalizer() |
text vectors, cosine similarity |
| one-hot encode, safe for new values | OneHotEncoder(handle_unknown="ignore", sparse_output=False) |
|
| merge rare categories | OneHotEncoder(min_frequency=20, handle_unknown="infrequent_if_exist") |
one infrequent_sklearn column |
| drop one dummy per feature | OneHotEncoder(drop="first") |
unpenalized linear models |
| integers for ordered categories | OrdinalEncoder(categories=[["basic", "standard", "premium"]]) |
default order is alphabetical |
| a code for unseen categories | OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1) |
trees |
| encode a high-cardinality column | TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42)) |
cross-fitted |
| use categories natively | category dtype + HistGradientBoosting*, LightGBM, XGBoost |
no encoding needed |
| fill blanks with the median | SimpleImputer(strategy="median") |
"most_frequent", "constant" |
| fill blanks and keep a flag | SimpleImputer(add_indicator=True) |
missingness can predict |
| fill from similar rows | KNNImputer(n_neighbors=5) |
scale first |
| fill from the other columns | IterativeImputer(random_state=42) |
from sklearn.experimental import enable_iterative_imputer |
| bins with fixed edges | pd.cut(x, bins=[...], right=False) |
exploration, reports |
bins learned in fit |
KBinsDiscretizer(n_bins=5, encode="ordinal") |
inside a pipeline |
| squares and products | PolynomialFeatures(degree=2, include_bias=False) |
|
| products only | PolynomialFeatures(interaction_only=True, include_bias=False) |
|
| smooth curves for linear models | SplineTransformer(n_knots=5, degree=3) |
|
| a cycle (month, hour) | sin(2πx/P) and cos(2πx/P), or SplineTransformer(extrapolation="periodic") |
always both columns |
| day of week | s.dt.day_of_week |
Monday = 0 |
| elapsed time | (snapshot - s).dt.days |
a fixed snapshot date |
| drop constant columns | VarianceThreshold(threshold=0.0) |
|
| keep the k best by a univariate test | SelectKBest(f_classif, k=10) |
filter |
| rank by non-linear dependence | mutual_info_classif(X, y, random_state=42) |
filter |
| drop features by model weights | RFE(model, n_features_to_select=10), RFECV |
wrapper |
| add features greedily by CV score | SequentialFeatureSelector(model, n_features_to_select=5) |
wrapper |
| keep features a model uses | SelectFromModel(Lasso(alpha=0.01)) |
embedded |
| keep column names in outputs | set_output(transform="pandas") |
before fit |
| evaluate without leakage | every learned step in a Pipeline |
then cross_val_score |
Scaling
Section titled “Scaling”| Scaler | Formula | Use when | Outliers | Key options |
|---|---|---|---|---|
StandardScaler |
the default for scale-sensitive models | pulled by them | with_mean=False for sparse |
|
MinMaxScaler |
a bounded range is required | very sensitive | feature_range, clip=True |
|
RobustScaler |
outliers you want to keep | robust | quantile_range=(25.0, 75.0) |
|
MaxAbsScaler |
sparse data | sensitive | ||
PowerTransformer |
Yeo-Johnson or Box-Cox, then standardize | skewed columns for linear models | reduced | method, standardize=True |
QuantileTransformer |
empirical CDF, then uniform or normal | heavy tails, odd shapes | robust | n_quantiles, output_distribution |
Normalizer |
each row divided by its norm | rows are vectors (text, counts) | — | norm="l2" |
| Model | Needs scaling? |
|---|---|
| KNN, k-means, SVM, PCA, neural networks | yes: distances and gradients follow the largest unit |
Ridge, Lasso, ElasticNet, LogisticRegression (penalized by default) |
yes: the penalty treats all weights alike |
LinearRegression |
no for predictions; yes to compare coefficients |
trees, forests, gradient boosting, HistGradientBoosting* |
no: splits depend only on the order of values |
from sklearn.preprocessing import ( PowerTransformer, QuantileTransformer, RobustScaler, StandardScaler,)
lot = h_train[["lot_sqft"]].dropna() # right-skewed, a few huge lotsprint(f"raw skew {lot['lot_sqft'].skew():.2f}")for step in [StandardScaler(), RobustScaler(), PowerTransformer(), QuantileTransformer(output_distribution="normal", random_state=42)]: z = step.set_output(transform="pandas").fit_transform(lot)["lot_sqft"] print(f"{type(step).__name__:<20} skew {z.skew():6.2f} max {z.max():6.2f}")raw skew 1.13StandardScaler skew 1.13 max 6.31RobustScaler skew 1.13 max 4.90PowerTransformer skew -0.03 max 3.46QuantileTransformer skew -0.01 max 5.20Linear scalers keep the shape, so the skew does not change. Only the power and quantile transforms change it.
Encoding categories
Section titled “Encoding categories”| Encoder | Output | Unknown categories | Rare categories | Use for |
|---|---|---|---|---|
OneHotEncoder |
one 0/1 column per category | handle_unknown="ignore": all zeros |
min_frequency, max_categories |
nominal columns, up to a few dozen levels |
OrdinalEncoder |
one integer column | handle_unknown="use_encoded_value", unknown_value=-1 |
min_frequency, max_categories |
ordered levels; trees |
TargetEncoder |
one column (one per class for multiclass) | the global target mean | shrunk to the mean (smooth="auto") |
high cardinality: zip codes, product ids |
category dtype |
the column itself | NaN in the model | — | HistGradientBoosting*, LightGBM, XGBoost |
pd.get_dummies |
dummy columns | not remembered between calls | — | exploration only |
handle_unknown= |
OneHotEncoder behavior |
|---|---|
"error" (default) |
raises on a new category |
"ignore" |
all zeros for that feature |
"infrequent_if_exist" |
maps it to the infrequent column (with min_frequency or max_categories) |
"warn" |
like "infrequent_if_exist" and warns |
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
train_hood = h_train[["neighborhood"]]new = pd.DataFrame({"neighborhood": ["Westfield", "Harbor Point"]}) # one unseenohe = OneHotEncoder(min_frequency=300, handle_unknown="infrequent_if_exist", sparse_output=False).fit(train_hood)print(ohe.get_feature_names_out())print(ohe.transform(new)) # Harbor Point -> the infrequent columnplan = OrdinalEncoder(categories=[["basic", "standard", "premium"]], handle_unknown="use_encoded_value", unknown_value=-1)print(plan.fit_transform(c_train[["plan"]].head(4)).ravel(), c_train["plan"].head(4).tolist())['neighborhood_Cedar Park' 'neighborhood_Maple Grove' 'neighborhood_Westfield' 'neighborhood_infrequent_sklearn'][[0. 0. 1. 0.] [0. 0. 0. 1.]][0. 1. 0. 0.] ['basic', 'standard', 'basic', 'basic']Target encoding replaces each category by a shrunken mean of the target. Shrinkage pulls small categories toward the global mean :
This holds for a number passed as smooth=m. The default smooth="auto" estimates the shrinkage per category from the target variance (empirical Bayes).
from sklearn.model_selection import StratifiedKFoldfrom sklearn.preprocessing import TargetEncoder
te = TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42))X_pay, y_pay = c_train[["payment_method"]], c_train["churned"]cross_fitted = te.fit_transform(X_pay, y_pay) # each row: from the other 4 foldsnaive = te.transform(X_pay) # every row: from all rows, its own target includedprint(pd.Series(te.encodings_[0], index=te.categories_[0]).round(3).to_dict())print(cross_fitted[:3].ravel().round(3), naive[:3].ravel().round(3)){'bank_transfer': 0.183, 'credit_card': 0.152, 'electronic_check': 0.246, 'paypal': 0.171}[0.249 0.174 0.153] [0.246 0.171 0.152]| Target encoding rule | Why |
|---|---|
fit_transform(X_train, y_train) for training rows |
cross-fitting: no row sees its own target |
transform(X_test) for new rows |
uses the means from all training rows |
never fit(X, y).transform(X) on the training rows |
that is naive target encoding and leaks |
pass a splitter to cv= |
shuffle= and random_state= are deprecated in scikit-learn 1.9 |
target_type="auto" |
binary, multiclass (one column per class) or continuous |
Missing values
Section titled “Missing values”| Tool | Fills with | Notes |
|---|---|---|
SimpleImputer(strategy="mean") |
column mean | the default |
SimpleImputer(strategy="median") |
column median | skewed columns |
SimpleImputer(strategy="most_frequent") |
the mode | categories and numbers |
SimpleImputer(strategy="constant", fill_value="missing") |
a fixed value | an explicit “missing” category |
add_indicator=True (any imputer) |
adds missingindicator_<col> columns |
when missingness itself predicts |
KNNImputer(n_neighbors=5, weights="distance") |
mean of the nearest rows | scale first; slow on big data |
IterativeImputer(random_state=42, max_iter=10) |
a model of each column on the others | experimental import; can warn about convergence |
MissingIndicator() |
the flags only | |
| native NaN support | — | trees, forests, HistGradientBoosting*, XGBoost, LightGBM |
from sklearn.impute import KNNImputer, SimpleImputer
cols = ["lot_sqft", "school_rating"]print(h_train[cols].isna().sum().to_dict())median = SimpleImputer(strategy="median", add_indicator=True)median.set_output(transform="pandas")print(median.fit_transform(h_train[cols]).columns.tolist())print(median.statistics_.tolist()) # learned on the training rowsknn = KNNImputer(n_neighbors=5).set_output(transform="pandas")filled = knn.fit_transform(h_train[["sqft", "lot_sqft"]])print(filled["lot_sqft"].isna().sum(), filled.shape){'lot_sqft': 71, 'school_rating': 70}['lot_sqft', 'school_rating', 'missingindicator_lot_sqft', 'missingindicator_school_rating'][7590.0, 6.0]0 (2250, 2)Binning
Section titled “Binning”| Tool | Edges | Notes |
|---|---|---|
pd.cut(x, bins=[18, 30, 45, 60, 120], right=False) |
yours | [a, b) intervals; labels with labels= |
pd.qcut(x, q=4, retbins=True) |
quantiles of x |
keep the edges to bin new data |
KBinsDiscretizer(n_bins, encode, strategy) |
learned in fit |
strategy: "quantile" (default), "uniform", "kmeans" |
encode= |
"onehot" (sparse, default), "onehot-dense", "ordinal" |
from sklearn.preprocessing import KBinsDiscretizer
binner = KBinsDiscretizer(n_bins=4, encode="ordinal", strategy="quantile")binner.fit(h_train[["sqft"]])print(binner.bin_edges_[0]) # learned quartile edgesprint(binner.transform(h_test[["sqft"]][:4]).ravel(), h_test["sqft"][:4].tolist())age_band = pd.cut(customers["age"], bins=[18, 30, 45, 60, 120], right=False)print(age_band.astype(str).value_counts(sort=False).to_dict())[ 550. 1360. 1745. 2210. 5710.][1. 0. 3. 2.] [1400, 1340, 2820, 2150]{'[18, 30)': 842, '[30, 45)': 1994, '[45, 60)': 1703, '[60, 120)': 461}Polynomial, interaction and spline features
Section titled “Polynomial, interaction and spline features”| Tool | Adds | Notes |
|---|---|---|
PolynomialFeatures(degree=2, include_bias=False) |
squares and pairwise products | features → columns |
PolynomialFeatures(interaction_only=True, include_bias=False) |
products only | no squares |
SplineTransformer(n_knots=5, degree=3) |
smooth piecewise curves per feature | better behaved than high powers |
SplineTransformer(extrapolation="periodic") |
a curve that wraps around | cycles: hour, month |
df["a"] * df["b"] |
one chosen interaction | cheap and readable |
| features | degree 2 | degree 3 | degree 2, interactions only |
|---|---|---|---|
| 5 | 20 | 55 | 15 |
| 10 | 65 | 285 | 55 |
| 20 | 230 | 1,770 | 210 |
from sklearn.preprocessing import PolynomialFeatures, SplineTransformer
two = h_train[["sqft", "year_built"]].head(2)poly = PolynomialFeatures(degree=2, include_bias=False).set_output(transform="pandas")print(poly.fit_transform(two).columns.tolist())spline = SplineTransformer(n_knots=4, degree=3).fit(h_train[["sqft"]])print(spline.n_features_out_, spline.get_feature_names_out()[:3])['sqft', 'year_built', 'sqft^2', 'sqft year_built', 'year_built^2']6 ['sqft_sp_0' 'sqft_sp_1' 'sqft_sp_2']Date and cyclical features
Section titled “Date and cyclical features”| Feature | pandas | Notes |
|---|---|---|
| year, month, day, hour | s.dt.year, s.dt.month, s.dt.day, s.dt.hour |
|
| day of week | s.dt.day_of_week |
Monday = 0; dt.weekday and dt.dayofweek warn in pandas 3 |
| day of year | s.dt.day_of_year |
|
| quarter, ISO week | s.dt.quarter, s.dt.isocalendar().week |
|
| weekend flag | s.dt.day_of_week >= 5 |
|
| month start or end | s.dt.is_month_start, s.dt.is_month_end |
|
| elapsed days | (pd.Timestamp("2024-12-31") - s).dt.days |
a fixed snapshot date, never “today” |
| cyclical pair | , | = 12 months, 7 days, 24 hours |
sold = pd.to_datetime(houses["sold_date"].iloc[[0, 700, 1400]])dates = pd.DataFrame({ "sold": sold.dt.date, "dow": sold.dt.day_of_week, "month": sold.dt.month, "age_days": (pd.Timestamp("2024-12-31") - sold).dt.days, "m_sin": np.sin(2 * np.pi * (sold.dt.month - 1) / 12).round(3), "m_cos": np.cos(2 * np.pi * (sold.dt.month - 1) / 12).round(3),})print(dates) sold dow month age_days m_sin m_cos0 2022-01-03 0 1 1093 0.000 1.000700 2022-09-22 3 9 831 -0.866 -0.5001400 2023-06-17 5 6 563 0.500 -0.866With one sine column, February and June both get 0.5. The cosine column tells them apart, so always add both.
Transforms for skewed values
Section titled “Transforms for skewed values”| Transform | Code | Domain | Inverse |
|---|---|---|---|
| log | np.log(x) |
np.exp |
|
| log1p | np.log1p(x) |
(zeros allowed) | np.expm1 |
| square root | np.sqrt(x) |
x ** 2 |
|
| Box-Cox | PowerTransformer(method="box-cox") |
inverse_transform |
|
| Yeo-Johnson | PowerTransformer() |
any real | inverse_transform |
| quantile | QuantileTransformer(output_distribution="normal") |
any | inverse_transform |
| in a pipeline | FunctionTransformer(np.log1p, inverse_func=np.expm1) |
||
| on the target | TransformedTargetRegressor(regressor, func=np.log, inverse_func=np.exp) |
automatic |
A model fitted on predicts the median, not the mean: np.exp of the prediction is a little below the mean in the original units.
Feature selection
Section titled “Feature selection”| Family | Tool | Scores features by | Cost | Watch out |
|---|---|---|---|---|
| filter | VarianceThreshold(threshold) |
variance | tiny | depends on units |
| filter | SelectKBest(f_classif, k), f_regression |
ANOVA F, linear correlation | tiny | one feature at a time; linear |
| filter | SelectKBest(mutual_info_classif, k), mutual_info_regression |
mutual information | small | noisy; set random_state |
| filter | chi2 |
chi-squared | tiny | non-negative features only |
| filter | SelectPercentile, SelectFpr, SelectFdr |
the same tests | tiny | other cut-offs |
| wrapper | RFE(estimator, n_features_to_select, step) |
refits, dropping the weakest | medium | needs coef_ or feature_importances_ |
| wrapper | RFECV(estimator, cv=5, scoring=...) |
RFE with CV to choose the count | high | n_features_ holds the count |
| wrapper | SequentialFeatureSelector(est, direction="forward", cv=5) |
CV score of each addition | high | many fits |
| embedded | Lasso(alpha), LogisticRegression(l1_ratio=1, solver="liblinear") |
L1 weights (zero = dropped) | small | scale first; picks one of correlated twins |
| embedded | tree feature_importances_ |
impurity decrease | small | favors continuous, high-cardinality features |
| embedded | SelectFromModel(estimator, threshold="median", max_features=...) |
any model’s weights or importances | small | wrap it in the pipeline |
| model-agnostic | permutation_importance(model, X_val, y_val) |
score drop when a column is shuffled | medium | on validation data |
from functools import partial
from sklearn.feature_selection import ( SelectFromModel, SelectKBest, mutual_info_regression,)from sklearn.linear_model import LassoCVfrom sklearn.pipeline import make_pipeline
num = ["sqft", "bedrooms", "bathrooms", "year_built", "garage_spaces", "has_pool", "condition", "distance_to_center_km"]Xh, yh = h_train[num], np.log(h_train["price"])kbest = SelectKBest(partial(mutual_info_regression, random_state=42), k=4)print(kbest.fit(Xh, yh).get_feature_names_out())lasso = make_pipeline( StandardScaler(), # L1 weights are comparable only on one scale SelectFromModel(LassoCV(cv=5, random_state=42), threshold="median"), # top half)print(lasso.fit(Xh, yh)[-1].get_feature_names_out(num))['sqft' 'bedrooms' 'bathrooms' 'distance_to_center_km']['sqft' 'year_built' 'condition' 'distance_to_center_km']Leakage rules
Section titled “Leakage rules”- Split first. Compute every statistic (mean, category list, bin edge, selected feature) on the training rows only.
- Put every learned step inside the pipeline that you pass to
cross_val_scoreor a search. - For each feature, ask: “Is this value known at prediction time?”
- Drop ids, row numbers and anything computed from the target or from events after the prediction date.
- Split by group when an entity has several rows (
GroupKFold); split by time for time-ordered data (TimeSeriesSplit). - Lag before you roll:
s.shift(1).rolling(7).mean(), neverrolling(7, center=True). - A score far above the baseline is a bug until proven otherwise. Score the top features one at a time.
| Leak | Example | Fix |
|---|---|---|
| preprocessing on all rows | StandardScaler().fit(X) before the split |
fit inside the pipeline |
| selection on all rows | SelectKBest().fit(X, y) before CV |
the selector inside the pipeline |
| naive target encoding | df.groupby(cat)[y].transform("mean") |
TargetEncoder.fit_transform |
| target leakage | price_per_sqft to predict price |
drop the column |
| post-outcome data | a “cancellation reason” to predict churn | only data from before the prediction date |
| duplicates across the split | the same house listed twice | deduplicate first or split by group |
| the future in features | centered windows, bfill, full-series scaling |
trailing windows; fit on the past only |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
fit_transform on the test set |
test data scaled by its own statistics | transform |
StandardScaler vs pandas .std() |
small mismatches | scikit-learn uses ddof=0, pandas ddof=1 |
MinMaxScaler on new extremes |
values outside 0–1 | clip=True if the model needs the range |
OrdinalEncoder() on ordered levels |
the order is alphabetical: basic, premium, standard | pass categories=[[...]] |
OneHotEncoder() on a new category |
ValueError: Found unknown categories |
handle_unknown="ignore" |
OneHotEncoder() output |
a sparse matrix | sparse_output=False (the old sparse= was removed) |
TargetEncoder.fit(X, y).transform(X) |
optimistic training scores | fit_transform cross-fits |
TargetEncoder(shuffle=True, random_state=42) |
FutureWarning in scikit-learn 1.9 |
cv=StratifiedKFold(5, shuffle=True, random_state=42) |
pd.get_dummies on train and test separately |
different columns | OneHotEncoder |
| duplicate column names | scikit-learn raises | add_prefix before concat |
np.log(0) |
-inf and a RuntimeWarning |
np.log1p; report errors after the inverse |
| one sine column for a cycle | two months share one value | add the cosine |
KBinsDiscretizer(strategy="uniform") on a skewed column |
most bins almost empty | "quantile" |
PolynomialFeatures(degree=3) on many columns |
thousands of columns, slow, overfits | chosen columns only, or splines |
include_bias=True (default) |
a constant column next to the model’s intercept | include_bias=False |
VarianceThreshold on raw columns |
keeps sqft, drops a useful flag |
scale first or use it only for constants |
| impurity importances | random ids rank high | permutation importance on validation data |
make_column_selector(dtype_include=object) |
Pandas4Warning |
dtype_include="str" |
KNNImputer on unscaled columns |
neighbors chosen by the largest unit | scale before imputing |
Learn more
Section titled “Learn more”- Module 33: feature engineering and its cheat sheet
- Module 34: the scikit-learn workflow for pipelines and
ColumnTransformer - Module 40: time series for lag and rolling features without leakage
- Master cheat sheet: scikit-learn API, models (which models need scaling) and pandas (dates and dtypes)