33. Feature engineering — Cheat sheet
The essentials of module 33 on one page. Every runnable block on this page is checked against its output. The examples use data/customers.csv and data/houses.csv from the data dictionary.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| learn parameters from training data | fit |
scaler.fit(X_train) |
| apply them to any data | transform |
scaler.transform(X_test) |
| fit and transform the training set | fit_transform |
X_train_s = scaler.fit_transform(X_train) |
| keep column names in the output | set_output(transform="pandas") |
StandardScaler().set_output(transform="pandas") |
| get the output column names | get_feature_names_out() |
encoder.get_feature_names_out() |
| scale to mean 0, std 1 | StandardScaler() |
linear models, SVM, PCA, KNN |
| scale to the range 0–1 | MinMaxScaler() |
bounded inputs |
| scale with outliers present | RobustScaler() |
median and IQR |
| one-hot encode, safe for new categories | OneHotEncoder(sparse_output=False, handle_unknown="ignore") |
region, payment_method |
| drop one dummy per feature | OneHotEncoder(drop="first") |
unregularized linear regression |
| merge rare categories | OneHotEncoder(min_frequency=20) or max_categories=10 |
long-tail categories |
| encode ordered categories | OrdinalEncoder(categories=[[...]]) |
contract, plan |
| encode a high-cardinality column | TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42)) |
postcodes, product ids |
| bin with fixed edges | pd.cut(x, bins=[...], right=False) |
age groups |
| bin with equal counts | pd.qcut(x, q=4) |
quartiles |
| learn bin edges on training data | KBinsDiscretizer(n_bins=5, strategy="quantile") |
inside a model |
| add squares and products | PolynomialFeatures(degree=2, include_bias=False) |
curved effects |
| add products only | PolynomialFeatures(interaction_only=True) |
interactions |
| one hand-made interaction | multiply two columns | df["mtm"] * df["support_tickets"] |
| day of week (Monday = 0) | s.dt.day_of_week |
weekly patterns |
| encode a cycle | np.sin(2 * np.pi * x / period) and np.cos(...) |
month, hour |
| elapsed time | (snapshot - s).dt.days |
days since signup |
| tame a right tail | np.log(x), np.log1p(x) with zeros |
prices, counts |
| undo the log | np.exp(p), np.expm1(p) |
predictions in dollars |
| drop near-constant features | VarianceThreshold(threshold=0.01) |
rare flags |
| rank by dependence | mutual_info_regression, mutual_info_classif |
non-linear filters |
| keep the k best by a test | SelectKBest(f_classif, k=10) |
univariate filter |
| eliminate recursively | RFE(model, n_features_to_select=10) |
wrapper |
| add features greedily by CV score | SequentialFeatureSelector(model, n_features_to_select=10, cv=3) |
wrapper |
| select with an L1 penalty | Lasso(alpha=0.01) on scaled data; SelectFromModel |
embedded |
| fit every step inside CV | make_pipeline(step, ..., model) + cross_val_score |
leakage-safe evaluation |
The transformer API
Section titled “The transformer API”| Method or attribute | Meaning |
|---|---|
fit(X, y=None) |
learn parameters; returns self |
transform(X) |
apply the learned parameters |
fit_transform(X, y=None) |
both, on the same data (training data only) |
name_ (trailing underscore) |
learned attribute: mean_, scale_, categories_, bin_edges_ |
get_feature_names_out() |
output column names |
set_output(transform="pandas") |
return a DataFrame instead of a NumPy array |
inverse_transform(X) |
back to the original units (scalers, OrdinalEncoder, OneHotEncoder) |
import numpy as npimport pandas as pdfrom sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
train = pd.DataFrame({"tenure_months": [1, 6, 24, 60], "tickets": [4, 2, 1, 0]})test = pd.DataFrame({"tenure_months": [12], "tickets": [3]})scaler = StandardScaler().set_output(transform="pandas").fit(train) # learn on trainprint(scaler.mean_, scaler.scale_.round(3))print(scaler.transform(test).round(3)) # apply to new rowsprint(scaler.inverse_transform(scaler.transform(test))) # back to the original units[22.75 1.75] [23.145 1.479] tenure_months tickets0 -0.464 0.845[[12. 3.]]Scaling
Section titled “Scaling”| Scaler | Formula | Output | Outliers | Key options |
|---|---|---|---|---|
StandardScaler |
(population ) | mean 0, std 1 | sensitive | with_mean=False for sparse data |
MinMaxScaler |
0–1 on training data | very sensitive | feature_range=(a, b), clip=True |
|
RobustScaler |
median 0, IQR 1 | robust | quantile_range=(25.0, 75.0) |
|
MaxAbsScaler |
−1 to 1, keeps zeros | sensitive | for sparse data |
| Model | Scale? |
|---|---|
| KNN, k-means, SVM, PCA, neural networks | yes |
Ridge, Lasso, ElasticNet, LogisticRegression (penalized by default) |
yes |
LinearRegression |
predictions no; comparable coefficients yes |
Decision tree, random forest, gradient boosting, HistGradientBoosting* |
no |
from sklearn.preprocessing import MinMaxScaler, RobustScaler
lots = pd.DataFrame({"lot_sqft": [4000, 6000, 7500, 9000, 39000]}) # one huge lotfor s in [StandardScaler(), MinMaxScaler(), RobustScaler()]: print(f"{type(s).__name__:<15}", s.fit_transform(lots).ravel().round(2))StandardScaler [-0.7 -0.54 -0.43 -0.31 1.98]MinMaxScaler [0. 0.06 0.1 0.14 1. ]RobustScaler [-1.17 -0.5 0. 0.5 10.5 ]Encoding categories
Section titled “Encoding categories”| Encoder | Output | Order | Unknown categories | Use for |
|---|---|---|---|---|
OneHotEncoder |
one 0/1 column per category | none | handle_unknown="ignore" → all zeros |
nominal, few categories |
OrdinalEncoder |
one integer column | alphabetical unless categories= |
handle_unknown="use_encoded_value", unknown_value=-1 |
ordinal; trees |
TargetEncoder |
one column (per class for multiclass) | from the target | the global target mean | high cardinality |
pd.get_dummies |
dummy columns | none | not remembered | exploration only |
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
train_cat = pd.DataFrame({"contract": ["one-year", "month-to-month", "two-year"], "region": ["East", "West", "East"]})new = pd.DataFrame({"contract": ["two-year"], "region": ["Central"]}) # unseen regionordinal = OrdinalEncoder(categories=[["month-to-month", "one-year", "two-year"]])print(ordinal.fit(train_cat[["contract"]]).transform(new[["contract"]]))onehot = OneHotEncoder(sparse_output=False, handle_unknown="ignore")print(onehot.fit(train_cat[["region"]]).get_feature_names_out())print(onehot.transform(new[["region"]])) # Central -> all zeros[[2.]]['region_East' 'region_West'][[0. 0.]]Target encoding with smoothing (mean of rows, global mean ):
from sklearn.model_selection import StratifiedKFold, train_test_splitfrom sklearn.preprocessing import TargetEncoder
customers = pd.read_csv("data/customers.csv")X_tr, X_te, y_tr, y_te = train_test_split( customers[["payment_method"]], customers["churned"], test_size=0.25, stratify=customers["churned"], random_state=42,)encoder = TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42))train_codes = encoder.fit_transform(X_tr, y_tr) # cross-fitted training valuestest_codes = encoder.transform(X_te) # full-training means for the test rowsprint(pd.Series(encoder.encodings_[0], index=encoder.categories_[0]).round(3))print(train_codes[:3].ravel().round(3), "<- out-of-fold values differ slightly")print(test_codes[:3].ravel().round(3), "<- test rows get the encodings above")bank_transfer 0.183credit_card 0.152electronic_check 0.246paypal 0.171dtype: float64[0.249 0.174 0.153] <- out-of-fold values differ slightly[0.152 0.246 0.246] <- test rows get the encodings above| Target encoding rule | Why |
|---|---|
fit_transform(X_train, y_train) on training rows |
cross-fitting: no row sees its own target |
transform(X_test) on test rows |
uses means from all training rows |
never fit(X_train, y).transform(X_train) |
that is naive target encoding and leaks |
pass a splitter to cv= |
shuffle= and random_state= are deprecated in scikit-learn 1.9 |
Binning
Section titled “Binning”| Tool | Edges | Notes |
|---|---|---|
pd.cut(x, bins=[...], labels=..., right=False) |
yours | right=False: [a, b) intervals |
pd.cut(x, bins=5) |
5 equal widths of x |
edges depend on the data passed |
pd.qcut(x, q=5, retbins=True) |
quantiles of x |
returns the edges to reuse on test data |
KBinsDiscretizer(n_bins, encode, strategy) |
learned in fit |
encode: "onehot", "onehot-dense", "ordinal"; strategy: "uniform", "quantile", "kmeans" |
from sklearn.preprocessing import KBinsDiscretizer
ages = pd.DataFrame({"age": [19, 23, 31, 38, 44, 52, 61, 70]})print(pd.cut(ages["age"], bins=[18, 30, 45, 60, 81], right=False).astype(str).tolist())codes, edges = pd.qcut(ages["age"], q=4, labels=False, retbins=True)print(codes.tolist(), edges)binner = KBinsDiscretizer(n_bins=4, encode="ordinal", strategy="uniform").fit(ages)print(binner.bin_edges_[0], binner.transform(ages).ravel())['[18, 30)', '[18, 30)', '[30, 45)', '[30, 45)', '[30, 45)', '[45, 60)', '[60, 81)', '[60, 81)'][0, 0, 1, 1, 2, 2, 3, 3] [19. 29. 41. 54.25 70. ][19. 31.75 44.5 57.25 70. ] [0. 0. 0. 1. 1. 2. 3. 3.]Polynomial and interaction features
Section titled “Polynomial and interaction features”Column count for features at degree (no bias): .
| features | degree 2 | degree 3 | degree 2, interaction_only |
|---|---|---|---|
| 3 | 9 | 19 | 6 |
| 8 | 44 | 164 | 36 |
| 10 | 65 | 285 | 55 |
| 20 | 230 | 1,770 | 210 |
from sklearn.preprocessing import PolynomialFeatures
two = pd.DataFrame({"log_sqft": [7.0, 8.0], "age": [10, 50]})poly = PolynomialFeatures(degree=2, include_bias=False).set_output(transform="pandas")print(poly.fit_transform(two))# A hand-made interaction: a separate size slope per area (keep the dummies too).areas = pd.get_dummies(pd.Series(["Lakeview", "Cedar Park"]), dtype=float)print(areas.mul(two["log_sqft"], axis=0).add_prefix("logsqft_x_")) log_sqft age log_sqft^2 log_sqft age age^20 7.0 10.0 49.0 70.0 100.01 8.0 50.0 64.0 400.0 2500.0 logsqft_x_Cedar Park logsqft_x_Lakeview0 0.0 7.01 8.0 0.0Date and time features
Section titled “Date and time features”| Feature | pandas | Note |
|---|---|---|
| year, month, day | s.dt.year, s.dt.month, s.dt.day |
|
| day of week | s.dt.day_of_week |
Monday = 0; dt.dayofweek is deprecated in pandas 3 |
| day of year | s.dt.day_of_year |
dt.dayofyear is deprecated in pandas 3 |
| hour | s.dt.hour |
|
| weekend flag | (s.dt.day_of_week >= 5).astype(int) |
|
| month end | s.dt.is_month_end |
|
| elapsed days | (pd.Timestamp("2024-12-31") - s).dt.days |
a fixed snapshot date, never “today” |
| cyclical pair | sin(2π·x/P), cos(2π·x/P) |
P = 12 months, 7 days, 24 hours; always both |
signup = pd.to_datetime(pd.Series(["2024-01-15", "2024-06-30", "2024-12-02"]))dates = pd.DataFrame({ "day_of_week": signup.dt.day_of_week, "month": signup.dt.month, "days_since": (pd.Timestamp("2024-12-31") - signup).dt.days, "month_sin": np.sin(2 * np.pi * (signup.dt.month - 1) / 12).round(3), "month_cos": np.cos(2 * np.pi * (signup.dt.month - 1) / 12).round(3),})print(dates) day_of_week month days_since month_sin month_cos0 0 1 351 0.0 1.0001 6 6 184 0.5 -0.8662 0 12 29 -0.5 0.866Transforms for skewed values
Section titled “Transforms for skewed values”| Transform | Code | Use when | Inverse |
|---|---|---|---|
| log | np.log(x) |
positive, right-skewed (prices) | np.exp |
| log1p | np.log1p(x) |
non-negative with zeros (counts) | np.expm1 |
| square root | np.sqrt(x) |
counts, milder skew | x ** 2 |
| as a transformer | FunctionTransformer(np.log1p, inverse_func=np.expm1) |
inside a pipeline | inverse_transform |
| log target | fit on np.log(y), predict, then np.exp |
errors in percent | module 35: TransformedTargetRegressor |
Feature selection
Section titled “Feature selection”| Family | Tool | Key parameters | Watch out |
|---|---|---|---|
| filter | VarianceThreshold |
threshold |
depends on units; use on flags or scaled data |
| filter | df.corrwith(y), df.corr() |
linear only; finds redundant pairs | |
| filter | mutual_info_regression / _classif |
random_state=42, discrete_features |
noisy estimates |
| filter | SelectKBest(score_func, k) |
f_classif, f_regression, mutual_info_* |
one feature at a time |
| wrapper | RFE(estimator, n_features_to_select) |
step |
ranks by coef_ or importances; scale first |
| wrapper | SequentialFeatureSelector |
direction, cv=3, scoring, n_features_to_select |
many fits; keep cv small |
| embedded | Lasso(alpha) |
larger alpha → fewer features |
scale first |
| embedded | LogisticRegression(l1_ratio=1.0, solver="liblinear") |
C (smaller → fewer) |
penalty="l1" is deprecated in 1.9 |
| embedded | tree feature_importances_ |
favors continuous and high-cardinality features | |
| embedded (meta-transformer) | SelectFromModel(estimator, threshold=...) |
max_features |
accepts any model with coef_ or feature_importances_ |
from sklearn.feature_selection import VarianceThreshold
flags = pd.DataFrame({"has_autopay": customers["has_autopay"], "many_tickets": (customers["support_tickets"] >= 6).astype(int)})selector = VarianceThreshold(threshold=0.01).fit(flags)print(selector.variances_.round(4), list(flags.columns[selector.get_support()]))[0.2492 0.0038] ['has_autopay']Data leakage checklist
Section titled “Data leakage checklist”- Split before you compute any statistic. For time data, split by date.
- Fit scalers, imputers, encoders, binners and selectors on training rows only.
- Put learned steps in a pipeline before
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.
- Remove duplicate rows before the split, or split by group (
GroupKFold). - Use trailing windows on time series:
shift(1)first, thenrolling. - Distrust a score far above the baseline. Score each feature alone and inspect the top coefficients or importances.
| Leak | Example | Fix |
|---|---|---|
| target leakage | price_per_sqft for a price model; a refund flag for churn |
drop the column |
| post-outcome data | retention call logged after a cancel request | use only data from before the prediction date |
| preprocessing on all rows | StandardScaler().fit(X) before the split |
fit on the training rows |
| selection on all rows | SelectKBest().fit(X, y) before CV |
selector inside the pipeline |
| naive target encoding | groupby(cat)[y].mean() mapped onto the training rows |
TargetEncoder.fit_transform |
| future in features | rolling(3, center=True) |
shift(1).rolling(3) |
| random split of a time series | train_test_split on daily data |
train on the past, test on the future |
from sklearn.feature_selection import SelectKBest, f_classiffrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_scorefrom sklearn.pipeline import make_pipeline
rng = np.random.default_rng(42)X_rand, y_rand = rng.normal(size=(300, 2000)), rng.permutation(np.repeat([0, 1], 150))folds = StratifiedKFold(5, shuffle=True, random_state=42)leaky = cross_val_score(LogisticRegression(), SelectKBest(f_classif, k=20).fit_transform(X_rand, y_rand), y_rand, cv=folds).mean()pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())safe = cross_val_score(pipe, X_rand, y_rand, cv=folds).mean()print(f"random labels: leaky {leaky:.2f}, honest {safe:.2f}")random labels: leaky 0.75, honest 0.47Gotchas
Section titled “Gotchas”fit_transformon the test set gives it its own statistics. Usetransform.StandardScaleruses the population standard deviation (ddof=0); pandas.std()usesddof=1.MinMaxScalerdoes not clip by default: new values can fall outside 0–1.OrdinalEncoderwithoutcategories=sorts alphabetically: basic, premium, standard.OneHotEncoderraisesValueError: Found unknown categorieson new categories unlesshandle_unknown="ignore".OneHotEncoderreturns a sparse matrix by default;sparse_output=Falsereturns a dense array (the oldsparse=name was removed).TargetEncoder.fit(X, y).transform(X)is not equal tofit_transform(X, y): onlyfit_transformcross-fits.pd.get_dummieson train and test separately can give different columns.- scikit-learn refuses DataFrames with duplicate column names; prefix new columns (
add_prefix). np.log(0)is-inf; usenp.log1p. Report errors afternp.exp, in the original units.- One sin column cannot tell two months apart; add the cos column.
KBinsDiscretizer(strategy="uniform")on a skewed column leaves most bins almost empty; use"quantile".PolynomialFeatureswithinclude_bias=True(the default) adds a constant column; setinclude_bias=Falsebefore a model with an intercept.- Impurity-based importances can rank random noise above real features. Check with a noise column or permutation importance (module 43).
VarianceThresholdon raw columns keepssqftand drops a useful 0/1 flag; variance depends on units.- Fold scores swing on small data. Report the mean and the spread, not one fold.