Feature Engineering: The Skill That Improves Models Most

A practical guide to feature engineering for machine learning — why it matters more than model choice on business data, the main feature types, handling categories, dates, text and missing values, avoiding leakage with point-in-time features and pipelines — with tested Python examples.

Quick Answer: Feature engineering is turning raw data into the inputs a model learns from. On structured business data it usually improves results more than switching algorithms. Good features come from domain understanding — recency, frequency, ratios, trends and calendar effects — and must be built point-in-time correct, using only information available at the moment of prediction. Wrapping preprocessing in a pipeline keeps it consistent and prevents leakage.

Beginners often spend most of their time trying different algorithms and tuning hyperparameters. Experienced data scientists spend most of theirs on features. The reason is simple: a model can only learn from what it is given. A gradient boosting model fed raw transaction rows will struggle; the same model fed "days since last order", "orders per month" and "change in spend over three months" will often perform far better with no tuning at all.

This guide explains how to think about features, the main types, how to handle categories, dates, text and missing values, and — most importantly — how to avoid leakage. The code examples were run on sample data to confirm they work.

Start From the Business Question

The best features come from asking what a domain expert would look at. For churn: has the customer's activity dropped, did they complain recently, did their plan change? For credit risk: how stretched are they, have they missed payments, how many recent loan enquiries? For demand: is it a festival week, a month-end, a sale period? Write these hypotheses down before coding. Each one usually becomes one or more features, and the list doubles as documentation of your reasoning — which interviewers love.

The Main Types of Features

Feature typeExamplesWhy it helps
AggregationsNumber of orders, total and average spend, maximum loan overdue daysSummarise many raw rows into one row per entity
Recency and frequencyDays since last purchase, orders per month, logins in last 30 daysCapture behaviour and engagement over time
RatiosEMI to income, failed to total payments, returns to ordersMake values comparable across customers of different sizes
Date and calendarDay of week, month-end flag, days to Diwali, salary-week flagCapture seasonality and Indian calendar effects
Trends and changesSpend this month versus last, change in balanceDetect shifts that often precede churn or default
TransformationsLog of amounts, binned age, capped outliersReduce skew and the influence of extreme values
InteractionsCity × product category, tenure × plan typeLet simpler models capture combined effects
Text-derivedComplaint keywords, sentiment, text lengthTurn unstructured text into model-ready signals

Building Customer Features in Python

Most business problems start with event-level data — orders, transactions, logins — that must be summarised to one row per customer, account or product. With an orders table containing order_id, customer_id, order_date and amount:

orders["order_date"] = pd.to_datetime(orders["order_date"])
snapshot = orders["order_date"].max() + pd.Timedelta(days=1)

cust = orders.groupby("customer_id").agg(
    n_orders=("order_id", "count"),
    total_spend=("amount", "sum"),
    avg_order=("amount", "mean"),
    first_order=("order_date", "min"),
    last_order=("order_date", "max"),
)
cust["recency_days"] = (snapshot - cust["last_order"]).dt.days
cust["tenure_days"] = (snapshot - cust["first_order"]).dt.days
cust["orders_per_month"] = cust["n_orders"] / (cust["tenure_days"] / 30 + 1)
cust["log_spend"] = np.log1p(cust["total_spend"])

These few lines create classic recency, frequency and monetary features, plus tenure, a normalised order rate and a log-transformed spend that reduces skew. Grouping by customer and aggregating is the most common feature engineering operation in industry.

Point-in-Time Correctness: The Rule That Matters Most

Every feature must be calculated using only data available at the moment the prediction would have been made. If you predict churn in March, features must use data up to the end of February — not purchases made in March or later. Breaking this rule is called leakage, and it produces models with impressive test scores that fail in production.

A subtle example: if "churned" is defined as no order in the next 120 days, a feature such as "days since last order" calculated on the full history partly is the label. The model looks brilliant and learns nothing useful. Fix the observation date, compute features only from data before it, and define the label only from data after it.

Other common leaks include features that are only filled in after the outcome — a "collections status" field in a default model — and aggregates computed over the whole dataset, including the test period. Always ask: would I have known this value on the prediction date?

Handling Categorical Features

EncodingWhen to useCaution
One-hotNominal categories with few levels, such as payment modeToo many columns for high-cardinality fields
OrdinalOrdered categories such as plan tiers or size bandsOnly where the order is meaningful
FrequencyHigh-cardinality fields such as pincode or product IDDifferent categories can share a frequency
Target encodingHigh-cardinality fields with a strong relation to the targetMust be fitted within training folds to avoid leakage

Tree-based models such as gradient boosting can handle simple encodings well; linear models usually need one-hot encoding. For fields such as pincode, product ID or merchant category, consider grouping rare values into an "other" bucket, or using frequency or carefully cross-validated target encoding.

Dates, Text and Missing Values

Dates

Raw dates are rarely useful directly. Extract day of week, month, quarter and month-end flags; compute durations such as tenure and days since an event; and add Indian calendar features — festival proximity, salary weeks, sale events and regional holidays — which often explain more variation than any other feature in retail and payments data.

Text

Simple text features go a long way: presence of keywords such as "refund" or "fraud", message length, counts of exclamation marks, and sentiment scores. For richer signals, TF-IDF vectors or embeddings from pre-trained language models turn text into numbers a model can use.

Missing values

Decide why data is missing before filling it. Median imputation works for many numeric fields; a separate "missing" category works for categories. When missingness itself carries information — no salary account linked, no email provided — add an indicator feature so the model can learn from it.

Use Pipelines to Keep It Consistent

Preprocessing steps such as imputation, scaling and encoding must be learned from training data only and then applied identically to new data. scikit-learn's pipelines enforce this:

from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression

num = ["orders_per_month", "avg_order", "log_spend", "tenure_days"]
cat = ["city", "signup_channel"]

prep = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median")),
                      ("scale", StandardScaler())]), num),
    ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                      ("onehot", OneHotEncoder(handle_unknown="ignore"))]), cat),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
model.fit(X_train, y_train)   # all preprocessing is learned from training data only

Because every transformation is fitted inside the pipeline, the same steps apply in cross-validation and in production, and there is no risk of scaling with statistics from the test set. Notice that recency_days is deliberately left out here, because in this example the churn label was derived from it — exactly the leakage trap described above.

Feature Selection and Importance

More features are not always better. Irrelevant or redundant features add noise, slow training and make models harder to explain. Start with a focused set built from your hypotheses, check importance using permutation importance or SHAP values, remove features that contribute nothing or are near-duplicates, and watch for features that are suspiciously important — they are often leaks. In regulated areas such as lending, prefer features you can explain to a customer or regulator.

A Worked Example: Credit Card Churn

A bank wants to predict which credit card customers will close their cards in the next three months. Raw data includes transactions, payments, customer profile and service interactions. Useful features might be: spend in the last month versus the three-month average; number of active spending categories; days since last transaction; payment-to-due ratio; count of declined transactions; complaints in the last 60 days; tenure; and whether a competing card's offer period has started. Each comes from a hypothesis about why people leave, each is computed as of the observation date, and together they usually outperform any amount of tuning on raw columns.

A Feature Engineering Checklist

Before training, run through these questions. Is every feature computed only from data before the observation date? Is the label defined only from data after it? Have skewed amounts been transformed or capped? Are categorical fields encoded appropriately for the model type? Is missingness handled deliberately, with indicators where it carries meaning? Are calendar and festival effects included where seasonality matters? Is every transformation inside a pipeline fitted on training data only? Can you explain, in one sentence, why each feature should help? And can the same features be produced reliably at prediction time? A "no" to any of these is worth fixing before tuning anything.

Features in Production

In a notebook, features are computed once. In production they must be computed every day or in real time, in exactly the same way, for new customers and transactions. Differences between how a feature was built for training and how it is built for scoring — known as training–serving skew — are one of the most common reasons models degrade after deployment. Larger teams address this with shared feature definitions or a feature store, which computes, stores and serves features consistently for both training and prediction, and records how each was defined. Even without a feature store, keeping feature logic in versioned, tested code rather than ad hoc notebooks goes a long way.

Common Mistakes

Computing features on the full dataset before splitting; using information from after the prediction date; one-hot encoding fields with thousands of values; ignoring skew in monetary amounts; filling missing values without thinking about why they are missing; adding dozens of features without checking whether they help; and failing to reproduce exactly the same features at prediction time in production. The last one causes many real-world model failures, which is why teams invest in shared feature definitions.

Feature Engineering in Interviews

Expect questions such as: How would you build features for churn, fraud or demand? What is data leakage, with an example? How do you encode a high-cardinality category? Why would you log-transform a feature? How do you handle missing values? Why use a pipeline? A strong answer names concrete features, explains the hypothesis behind each, and mentions point-in-time correctness without being asked.

Our Machine Learning course teaches feature engineering through real projects, and the Data Science course builds the Python, SQL and statistics foundations it depends on.

People Also Ask / FAQ

Is feature engineering still needed with deep learning?

Much less for images, audio and text, where networks learn features. For tabular business data it remains the biggest lever on performance.

How many features should a model have?

There is no fixed number. Start with a focused set based on hypotheses, then add or remove based on validation results and importance.

Do tree models need feature scaling?

No. Decision trees, random forests and gradient boosting are insensitive to scaling; linear models, KNN and SVMs need it.

What is the most common feature engineering mistake?

Data leakage — using information that would not be available at prediction time.

Can AutoML do feature engineering for me?

It can generate many generic features, but domain-driven features and leakage checks still need human judgement.

Build Better Models With Better Features

Live classes, real projects and interview practice — online and in select cities across India Explore the Machine Learning Course