Skip to content

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.

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
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 np
import pandas as pd
from 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 train
print(scaler.mean_, scaler.scale_.round(3))
print(scaler.transform(test).round(3)) # apply to new rows
print(scaler.inverse_transform(scaler.transform(test))) # back to the original units
Output
[22.75 1.75] [23.145 1.479]
tenure_months tickets
0 -0.464 0.845
[[12. 3.]]
Scaler Formula Output Outliers Key options
StandardScaler (x−μ)/σ(x - \mu) / \sigma (population σ\sigma) mean 0, std 1 sensitive with_mean=False for sparse data
MinMaxScaler (x−min⁡)/(max⁡−min⁡)(x - \min) / (\max - \min) 0–1 on training data very sensitive feature_range=(a, b), clip=True
RobustScaler (x−median)/(Q3−Q1)(x - \text{median}) / (Q_3 - Q_1) median 0, IQR 1 robust quantile_range=(25.0, 75.0)
MaxAbsScaler x/max⁡∣x∣x / \max \lvert x \rvert −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 lot
for s in [StandardScaler(), MinMaxScaler(), RobustScaler()]:
print(f"{type(s).__name__:<15}", s.fit_transform(lots).ravel().round(2))
Output
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 ]
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 region
ordinal = 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
Output
[[2.]]
['region_East' 'region_West']
[[0. 0.]]

Target encoding with smoothing mm (mean yˉc\bar{y}_c of ncn_c rows, global mean yˉ\bar{y}):

encoding(c)=nc yˉc+m yˉnc+m\text{encoding}(c) = \frac{n_c\,\bar{y}_c + m\,\bar{y}}{n_c + m}
from sklearn.model_selection import StratifiedKFold, train_test_split
from 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 values
test_codes = encoder.transform(X_te) # full-training means for the test rows
print(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")
Output
bank_transfer 0.183
credit_card 0.152
electronic_check 0.246
paypal 0.171
dtype: 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
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())
Output
['[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.]

Column count for nn features at degree dd (no bias): (n+dd)−1\binom{n+d}{d} - 1.

nn 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_"))
Output
log_sqft age log_sqft^2 log_sqft age age^2
0 7.0 10.0 49.0 70.0 100.0
1 8.0 50.0 64.0 400.0 2500.0
logsqft_x_Cedar Park logsqft_x_Lakeview
0 0.0 7.0
1 8.0 0.0
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)
Output
day_of_week month days_since month_sin month_cos
0 0 1 351 0.0 1.000
1 6 6 184 0.5 -0.866
2 0 12 29 -0.5 0.866
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
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()]))
Output
[0.2492 0.0038] ['has_autopay']
  1. Split before you compute any statistic. For time data, split by date.
  2. Fit scalers, imputers, encoders, binners and selectors on training rows only.
  3. Put learned steps in a pipeline before cross_val_score or a search.
  4. For each feature, ask: “Is this value known at prediction time?”
  5. Drop ids, row numbers and anything computed from the target.
  6. Remove duplicate rows before the split, or split by group (GroupKFold).
  7. Use trailing windows on time series: shift(1) first, then rolling.
  8. 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_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from 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}")
Output
random labels: leaky 0.75, honest 0.47
  • fit_transform on the test set gives it its own statistics. Use transform.
  • StandardScaler uses the population standard deviation (ddof=0); pandas .std() uses ddof=1.
  • MinMaxScaler does not clip by default: new values can fall outside 0–1.
  • OrdinalEncoder without categories= sorts alphabetically: basic, premium, standard.
  • OneHotEncoder raises ValueError: Found unknown categories on new categories unless handle_unknown="ignore".
  • OneHotEncoder returns a sparse matrix by default; sparse_output=False returns a dense array (the old sparse= name was removed).
  • TargetEncoder.fit(X, y).transform(X) is not equal to fit_transform(X, y): only fit_transform cross-fits.
  • pd.get_dummies on 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; use np.log1p. Report errors after np.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".
  • PolynomialFeatures with include_bias=True (the default) adds a constant column; set include_bias=False before 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).
  • VarianceThreshold on raw columns keeps sqft and 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.