Sub topic 5
Turning behaviour into features
This chapter assumes you can read pandas code and know basic statistics such as mean, skew and standard deviation. You should also know what the customer data foundation and the three segmentation approaches are from earlier chapters. Here you will learn how to turn raw event logs into the numeric columns that clustering and predictive models use.
What a feature is
A feature is one number (or category) per customer that describes something about their behaviour at a point in time. Raw data is usually a log of events: page views, orders, email opens, support tickets. Segmentation algorithms need one row per customer. Feature engineering is the step that collapses many event rows into that one row.
The choices you make here decide what your segments can express. K-means on three well-built features will give clearer groups than k-means on fifty noisy ones.
The working model
Each feature has four design decisions:
- Entity. What does one row represent? Usually one customer ID. If identity resolution is weak, the same person may be split across rows, and every feature will be understated.
- Cutoff date. The "as of" moment. Only events at or before it may be used.
- Window. How far back to look from the cutoff, such as 30, 90 or 180 days.
- Aggregation. How events are summarised: count, sum, mean, maximum, time since last.
RFM as a starting set
RFM is the classic feature set for customer value:
- Recency: days since the last purchase. Lower usually means more engaged.
- Frequency: number of purchases in the window.
- Monetary: total (or average) spend in the window.
RFM works well because it needs only order data, it is easy to explain to marketers, and it predicts future behaviour reasonably well. It is a baseline, not a ceiling.
Beyond RFM: behavioural features
Once RFM works, add features that describe how customers behave, not only how much they spend.
| Behaviour | Example feature | What it tells you |
|---|---|---|
| Browsing | Sessions in last 30 days | Current interest |
| Open rate over last 10 sends | Channel responsiveness | |
| Purchases | Share of orders with a discount | Price sensitivity |
| Catalogue | Number of distinct categories bought | Breadth of interest |
| Timing | Mean days between orders | Natural purchase rhythm |
| Trend | Orders in last 30 days divided by orders in prior 30 | Rising or falling engagement |
Ratios and trends are often more useful than raw counts. A customer with 4 orders in the last 30 days and 0 before is different from one with a steady 2 per month, even when the 60-day totals match.
Building features from events
The function below takes an order log, a cutoff date and a window. It returns one row per customer. Customers with no orders in the window stay in the table with zero frequency and spend, and with recency set to the window length, so they are not silently dropped.
import numpy as np
import pandas as pd
def build_rfm(orders, customer_ids, as_of, window_days=180):
"""Return one RFM row per customer using only orders in (as_of - window, as_of]."""
as_of = pd.Timestamp(as_of)
start = as_of - pd.Timedelta(days=window_days)
window = orders[(orders["order_date"] > start) & (orders["order_date"] <= as_of)]
summary = window.groupby("customer_id").agg(
last_order=("order_date", "max"),
frequency=("amount", "size"),
monetary=("amount", "sum"),
)
features = pd.DataFrame(index=pd.Index(customer_ids, name="customer_id"))
features = features.join(summary)
features["recency_days"] = (as_of - features["last_order"]).dt.days
features["recency_days"] = features["recency_days"].fillna(window_days)
features["frequency"] = features["frequency"].fillna(0)
features["monetary"] = features["monetary"].fillna(0.0)
# Spend is right-skewed, so compress it before scaling.
features["log_monetary"] = np.log1p(features["monetary"])
return features[["recency_days", "frequency", "monetary", "log_monetary"]]
orders = pd.DataFrame({
"customer_id": [1, 1, 1, 2, 2, 3],
"order_date": pd.to_datetime([
"2026-09-02", "2026-10-15", "2026-11-20",
"2026-08-01", "2026-09-10", "2026-03-05",
]),
"amount": [40.0, 55.0, 80.0, 120.0, 60.0, 25.0],
})
rfm = build_rfm(orders, customer_ids=[1, 2, 3, 4], as_of="2026-11-26")
print(rfm)Customer 3's only order is older than 180 days, and customer 4 has no orders. Both end up with frequency 0 and recency_days 180. That is a deliberate, documented choice: "no recent activity" is information, not missing data.
Missing values: three different meanings
A blank can mean different things, and each needs a different treatment.
- No events happened. Fill with 0 for counts and sums. This is a real zero.
- Never observed. The customer has no email history because they never subscribed. Filling with 0 would claim they open no emails. Use a separate flag such as
has_email_historyand fill the rate with a neutral value, or leave it out of the model. - Data error. A missing date caused by a pipeline fault. Fix upstream or exclude the row.
Treating all three as zero is one of the most common mistakes, and it quietly creates a "low engagement" cluster made of people you simply know nothing about.
Transformations
Skew
Spend and event counts usually have a long right tail: most customers spend little and a few spend a lot. K-means measures straight-line distance, so a handful of very large values dominate it. Apply log1p (the log of 1 plus the value, which handles zeros) to compress the tail. Do this for monetary value, session counts and similar columns.
Scaling
After transforming, put features on a comparable scale. Standardisation subtracts the mean and divides by the standard deviation. Without it, a column measured in dollars outweighs one measured in days. Fit the scaler on your training population, and save it. Applying a freshly fitted scaler to next month's data shifts what "high" means and changes segment boundaries without anyone deciding to change them.
Capping
For extreme outliers such as a single B2B order of 50,000 in a consumer base, cap values at a high percentile (for example the 99th). Record the cap in your documentation so it can be reproduced.
Leakage and time
Leakage means a feature contains information that would not have been available at the moment you use it. For clustering the damage is milder than in prediction, but it still appears.
For predictive segments, a common failure is computing features and the label over overlapping periods. For example, you compute "orders in the last 90 days" up to today and also label customers as "churned" based on the next 30 days from the same date. Check that every feature uses only data up to the cutoff, and every label uses only data after it.
Choosing and pruning features
More features do not mean better segments. Use these checks:
- Correlation. If two features correlate above roughly 0.9 (for example total orders and total spend in a small shop), they double-count one idea in distance calculations. Keep one.
- Variance. A feature that is nearly constant carries no information. Drop it.
- Interpretability. If you cannot explain a feature to a marketer in a sentence, you will struggle to name the segment it creates.
- Stability. Compute the feature on two adjacent months. If the distribution jumps without a business reason, the feature depends on a fragile data source.
- Consent. Only use data that your consent records allow for this purpose. Dropping a feature later, after segments are in production, is expensive.
Common errors
| Error | Symptom | Fix |
|---|---|---|
| Unscaled features | One column decides all clusters | Standardise after transforming |
| Skew left in place | One giant cluster plus tiny outlier clusters | Apply `log1p` or cap |
| Zero-filling unknowns | A low-engagement segment full of new or unsubscribed people | Add flags, separate unknown from zero |
| Moving cutoff | Segments change between runs for no reason | Pass an explicit as-of date |
| Mixed windows | Frequency over 90 days, spend over lifetime | Use one window per feature family or name them clearly |
| Duplicate identities | Customers appear as several light users | Resolve identity before aggregating |
| Refitting the scaler on each run | Segment meaning drifts silently | Persist and version the scaler |
Checking your features before modelling
Before clustering, run quick checks on the feature table:
checks = rfm.describe().T[["mean", "std", "min", "max"]]
print(checks)
print(rfm.corr().round(2))
print(rfm.isna().sum())Look for impossible values (negative recency), unexpected nulls, and correlations that suggest redundancy. Here, monetary and log_monetary are intentionally the same idea in two forms. Keep only log_monetary when you pass the table to the model.
Exercise
A feature table has a column emailopenrate that is 0.0 for customers who never subscribed to email and also for subscribers who opened none of their last 10 emails. Why is this a problem for clustering, and what two changes would you make?
Show answer
The value 0.0 mixes "never observed" with "observed and zero". A clustering model will place unsubscribed customers in the same low-engagement group as subscribers who ignore email, so the segment name and any marketing action based on it will be wrong. Add a binary flag such as hasemailhistory, and either fill the rate for non-subscribers with a neutral value (for example the population mean) or exclude emailopenrate from the model for those customers. Then check that the resulting segments do not split purely on the flag unless that split is intended.
Exercise
You rebuild last month's segments today by running a feature function that filters orders with "the last 90 days from now". The segments differ from the ones used in last month's campaign, even though the data has not changed. What is the cause and what is the fix?
Show answer
The function uses the current date as its cutoff, so the 90-day window has moved and includes or excludes different orders. Add an as_of parameter, pass last month's cutoff date, and store that date with each segment run so any run can be reproduced.