Feature engineering means turning raw data into inputs that help a model learn. A model only sees the columns you give it: it cannot know that a timestamp at 2am on a Sunday is unusual, that spend per visit matters more than total spend, or that “Mancheste” is a typo. On tabular business data, thoughtful features often improve results more than switching to a fancier algorithm.
This tutorial covers the core techniques for tabular data: handling missing values, encoding categories, scaling, transforming skewed numbers, creating date, ratio and aggregate features, and binning – all inside scikit-learn pipelines so nothing leaks from test data. It finishes with a before-and-after comparison on a simulated dataset.
Ground rules
- Only use information available at prediction time. A “cancellation_date” column will predict churn perfectly in training and is useless in production. This is target leakage.
- Learn transformations from training data only. Means for imputation, scaling parameters and category lists must come from the training set. Pipelines handle this; see Train/Test Split Explained.
- Validate every feature idea with cross-validation rather than intuition alone.
The example dataset
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
n = 4000
df = pd.DataFrame({
"signup_date": pd.to_datetime("2023-01-01") + pd.to_timedelta(rng.integers(0, 500, n), unit="D"),
"last_login": pd.Timestamp("2024-06-30") - pd.to_timedelta(rng.exponential(20, n).astype(int), unit="D"),
"visits": rng.poisson(12, n) + 1,
"total_spend": rng.gamma(2, 60, n).round(2),
"plan": rng.choice(["Basic", "Plus", "Pro"], n, p=[0.6, 0.3, 0.1]),
"region": rng.choice(["London", "North", "Midlands", "Scotland", "Wales"], n),
"age": rng.normal(40, 12, n).round(),
})
df.loc[rng.random(n) < 0.08, "age"] = np.nan # some missing ages
snapshot = pd.Timestamp("2024-07-01")
days_inactive = (snapshot - df["last_login"]).dt.days
spend_per_visit = df["total_spend"] / df["visits"]
score = -2 + 0.05 * days_inactive - 0.02 * spend_per_visit + (df["plan"] == "Basic") * 0.8
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-score))).astype(int)
print(df.head())
print("Churn rate:", df["churned"].mean().round(3))
We simulated churn so that it depends on days since last login and spend per visit – neither of which exists as a raw column. That mirrors real life: the useful signal is often a combination or transformation of what is stored.
Step 1: Missing values
Most scikit-learn models cannot handle NaN. SimpleImputer fills gaps with the median (numeric) or most frequent value (categorical). Adding a missing-indicator column lets the model learn whether missingness itself is informative – sometimes customers who skip a field behave differently:
from sklearn.impute import SimpleImputer
imp = SimpleImputer(strategy="median", add_indicator=True)
print(imp.fit_transform(df[["age"]])[:5])
The second output column is 1 where age was missing. The cleaning side of missing data is covered in Cleaning Messy Data with Pandas.
Step 2: Encoding categorical variables
- One-hot encoding creates a 0/1 column per category. The safe default for nominal categories (region, plan) with a manageable number of values.
- Ordinal encoding maps categories to ordered integers. Only appropriate when there is a genuine order (e.g. Basic < Plus < Pro) – or for tree-based models, which cope with arbitrary codes.
- High-cardinality categories (thousands of postcodes or product IDs) need grouping of rare levels, target encoding with proper cross-fitting, or a coarser level such as postcode area.
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder
ohe = OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=0.05, sparse_output=False)
print(ohe.fit(df[["region"]]).get_feature_names_out())
ord_enc = OrdinalEncoder(categories=[["Basic", "Plus", "Pro"]])
print(ord_enc.fit_transform(df[["plan"]].head()).ravel())
min_frequency groups rare categories together, which reduces noise and copes with categories that appear later.
Step 3: Scaling
Linear models, k-nearest neighbours, SVMs and neural networks are sensitive to feature scale; tree-based models are not. StandardScaler (mean 0, standard deviation 1) is the usual choice; RobustScaler uses the median and interquartile range and is less affected by outliers.
Step 4: Transform skewed numbers
Money, counts and durations are often right-skewed: most values small, a few very large. A log transform compresses the long tail, which helps linear models in particular:

print("Skew before:", df["total_spend"].skew().round(2))
print("Skew after log1p:", np.log1p(df["total_spend"]).skew().round(2))
log1p computes log(1 + x), which is safe for zeros. Inside a pipeline, use FunctionTransformer(np.log1p).
Step 5: Date and time features
Raw timestamps are meaningless to most models. Convert them into durations and calendar features relative to a fixed snapshot date:

def add_date_features(d, snapshot=pd.Timestamp("2024-07-01")):
d = d.copy()
d["tenure_days"] = (snapshot - d["signup_date"]).dt.days
d["days_inactive"] = (snapshot - d["last_login"]).dt.days
d["signup_month"] = d["signup_date"].dt.month
d["signup_weekend"] = (d["signup_date"].dt.dayofweek >= 5).astype(int)
return d
print(add_date_features(df)[["tenure_days", "days_inactive", "signup_month", "signup_weekend"]].head())
The snapshot must be the point at which you would make the prediction, not “today” at training time, otherwise durations shift between training and deployment. More date techniques are in Dates and Times in Pandas.
For cyclical features such as month or hour, where December is next to January, sine and cosine encoding can help linear models: np.sin(2 * np.pi * month / 12) and the matching cosine.
Step 6: Ratio and interaction features
Ratios often capture behaviour better than raw totals. Someone who spent £600 over 50 visits behaves differently from someone who spent £600 in 2.
def add_ratios(d):
d = d.copy()
d["spend_per_visit"] = d["total_spend"] / d["visits"].clip(lower=1)
d["visits_per_month"] = d["visits"] / (d["tenure_days"] / 30).clip(lower=1)
return d
Guard against division by zero (here with clip). Domain knowledge is your best source of ratio ideas: conversion rates, utilisation, growth rates, share of spend in a category.
Step 7: Aggregate features from transaction tables
When your raw data is a log of events (orders, logins), summarise it per entity with groupby and join the result back:
tx = pd.DataFrame({
"customer_id": rng.integers(0, 100, 1000),
"amount": rng.gamma(2, 20, 1000).round(2),
"date": pd.to_datetime("2024-01-01") + pd.to_timedelta(rng.integers(0, 180, 1000), unit="D"),
})
cutoff = pd.Timestamp("2024-06-01")
hist = tx[tx["date"] < cutoff] # only data before the prediction point
agg = hist.groupby("customer_id").agg(
n_orders=("amount", "size"),
avg_order=("amount", "mean"),
max_order=("amount", "max"),
last_order=("date", "max"),
)
agg["days_since_order"] = (cutoff - agg["last_order"]).dt.days
print(agg.drop(columns="last_order").head())
The cut-off filter is essential: aggregates must use only events before the moment of prediction.
Step 8: Binning
Binning turns a number into ranges (for example age bands). It can capture non-linear effects for linear models and makes results easy to explain, but it throws away detail. Use pd.cut for fixed edges or scikit-learn’s KBinsDiscretizer inside a pipeline. Do not bin by default; try it when a relationship is clearly non-linear.
Step 9: Put it together and measure the gain
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, FunctionTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, StratifiedKFold
cv = StratifiedKFold(5, shuffle=True, random_state=0)
y = df["churned"]
# Baseline: raw numeric columns + plan
raw_cols = ["visits", "total_spend", "age"]
base_pre = ColumnTransformer([
("num", Pipeline([("imp", SimpleImputer(strategy="median")), ("sc", StandardScaler())]), raw_cols),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])
base = Pipeline([("pre", base_pre), ("lr", LogisticRegression(max_iter=1000))])
base_auc = cross_val_score(base, df, y, cv=cv, scoring="roc_auc").mean()
# Engineered features
feat = add_ratios(add_date_features(df))
num_cols = ["visits", "age", "tenure_days", "days_inactive", "spend_per_visit", "visits_per_month"]
eng_pre = ColumnTransformer([
("num", Pipeline([("imp", SimpleImputer(strategy="median", add_indicator=True)),
("sc", StandardScaler())]), num_cols),
("log", Pipeline([("log", FunctionTransformer(np.log1p)), ("sc", StandardScaler())]), ["total_spend"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan", "region"]),
])
eng = Pipeline([("pre", eng_pre), ("lr", LogisticRegression(max_iter=1000))])
eng_auc = cross_val_score(eng, feat, y, cv=cv, scoring="roc_auc").mean()
print(f"Baseline ROC AUC: {base_auc:.3f}")
print(f"Engineered ROC AUC: {eng_auc:.3f}")
The engineered model scores clearly higher, because it can now see days of inactivity and spend per visit – the drivers we built into the simulation. On real data the gains are rarely this clean, which is exactly why every idea should be tested with cross-validation. Note that the ratio and date features here are computed row by row and use no statistics from other rows, so creating them before cross-validation does not leak; anything that learns from data (imputation, scaling, encoding) stays inside the pipeline.
Common mistakes
- Target leakage: features that are only known after the outcome.
- Fitting transformations on all data before splitting.
- Using “today” instead of a fixed snapshot date for durations.
- One-hot encoding thousands of categories without grouping rare ones.
- Creating hundreds of features blindly, which adds noise and overfitting risk.
- Not checking that features behave the same in production as in training data.
FAQ
Do tree-based models need feature engineering?
Less scaling and encoding, but ratios, date features and aggregates still help, because trees cannot easily compute divisions or differences between columns.
Can I automate feature engineering?
Libraries exist that generate many candidate features automatically, but domain-driven features are usually more useful and easier to explain. Automated approaches also increase leakage risk if not used carefully.
How do I know which features matter?
Look at coefficients (for linear models), permutation importance (sklearn.inspection.permutation_importance) and, above all, cross-validated performance with and without the feature.
Next steps
Apply these features in logistic regression or linear regression, and evaluate them properly with cross-validation and classification metrics.



