An online shop has 400 customers and thousands of orders. Sending everyone the same offer wastes money. In this project you will group customers by how they shop, using a classic method called RFM and the k-means algorithm. You will turn raw orders into three numbers per customer, choose the number of groups, and give each group a name the marketing team can act on.
In this project you will
- Turn an order table into Recency, Frequency and Monetary values with pandas
- Prepare skewed spending data with a log and scaling
- Pick the number of clusters with the silhouette score
- Profile each cluster and give it a business name
- Suggest an action for each customer segment
You should know k-means clustering, feature scaling and pandas groupby.
Step 1: From Orders to RFM
RFM describes each customer with three numbers:
- Recency: days since their last order. Smaller is better.
- Frequency: how many orders they placed.
- Monetary: how much they spent in total.
Our data is made up, but it mimics a real shop. Some customers are loyal regulars, some place a few very large orders, some are new, and some have stopped buying. The model is not told who is who.
import numpy as np
import pandas as pd
# Fake order history for 400 customers of an online shop in 2026
rng = np.random.default_rng(11)
kinds = rng.choice(["loyal", "big", "new", "lapsed"], 400, p=[0.3, 0.15, 0.25, 0.3])
rows = []
for cid, kind in enumerate(kinds, start=1001):
n, last, amount = { # orders, days since last order, typical bill
"loyal": (rng.integers(12, 25), rng.integers(1, 20), 600),
"big": (rng.integers(3, 7), rng.integers(5, 40), 4000),
"new": (rng.integers(1, 3), rng.integers(1, 25), 700),
"lapsed": (rng.integers(2, 6), rng.integers(150, 300), 500),
}[kind]
for k in range(n):
days_ago = last if k == 0 else rng.integers(last, 330)
rows.append((cid, 300 - days_ago, round(rng.gamma(4, amount / 4))))
orders = pd.DataFrame(rows, columns=["customer", "day", "amount_tk"])
orders["date"] = pd.Timestamp("2026-01-01") + pd.to_timedelta(orders["day"], unit="D")
orders = orders.drop(columns="day")
print(orders.head(3).to_string(index=False))
print("orders:", len(orders), " customers:", orders["customer"].nunique())
# RFM: Recency, Frequency, Monetary value for each customer
today = orders["date"].max() + pd.Timedelta(days=1)
rfm = orders.groupby("customer").agg(
recency=("date", lambda d: (today - d.max()).days),
frequency=("date", "count"),
monetary=("amount_tk", "sum"),
)
print()
print(rfm.head(3))
print()
print(rfm.describe().loc[["mean", "min", "max"]].round(0))
rfm.to_csv("rfm.csv") # step 2 starts from this file
Output
customer amount_tk date
1001 112 2026-10-17
1001 683 2026-03-04
1001 661 2026-03-05
orders: 3243 customers: 400
recency frequency monetary
customer
1001 11 21 12011
1002 7 2 2013
1003 1 1 579
recency frequency monetary
mean 71.0 8.0 7349.0
min 1.0 1.0 185.0
max 299.0 24.0 34637.0
- We measure recency from “today”, one day after the last order in the data. In a live system you would use the real current date.
groupby("customer").agg(...)builds all three columns in one step. Thelambdafinds each customer’s latest order date.- Customer 1001 ordered 11 days ago, 21 times, and spent 12,011 taka. Customer 1003 has one recent small order.
- Spending runs from 185 to 34,637 taka, with a mean of 7,349. That long tail would let a few big spenders control the clustering, so step 2 takes logs first.
- The table is saved to
rfm.csvso step 2 can start from it.
Step 2: Find and Name the Segments
k-means uses distances, so all three columns must be on a fair scale. We apply log1p to squash the long tails, then StandardScaler. Next we try 2 to 6 clusters and compare silhouette scores. A higher score means points sit closer to their own cluster than to the next one.
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
rfm = pd.read_csv("rfm.csv", index_col="customer")
# Spending is very skewed, so take logs before scaling
X = StandardScaler().fit_transform(np.log1p(rfm))
print("k silhouette")
for k in range(2, 7):
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X)
print(f"{k} {silhouette_score(X, labels):.3f}")
rfm["segment"] = KMeans(n_clusters=4, n_init=10, random_state=0).fit_predict(X)
profile = rfm.groupby("segment").agg( # the typical customer per segment
customers=("recency", "size"),
recency=("recency", "median"),
frequency=("frequency", "median"),
monetary=("monetary", "median"),
)
def name(row):
if row.recency > 90:
return "Slipping away"
if row.frequency >= 10:
return "Loyal regulars"
if row.monetary >= 10000:
return "Big spenders"
return "New customers"
profile["name"] = profile.apply(name, axis=1)
print()
print(profile.sort_values("monetary", ascending=False).to_string())
Output
k silhouette
2 0.540
3 0.628
4 0.640
5 0.565
6 0.510
customers recency frequency monetary name
segment
3 66 22.0 4.0 16637.5 Big spenders
0 133 10.0 19.0 10950.0 Loyal regulars
1 109 220.0 3.0 1567.0 Slipping away
2 92 12.0 1.5 1084.5 New customers
- The silhouette score peaks at k = 4 (0.640), so we use 4 segments. It also matches a number the marketing team can handle.
- The profile uses the median, which is not pulled around by a few extreme customers.
- Cluster numbers from k-means have no meaning, so we name each one with simple rules. We wrote these rules after reading the profile table, using cut-offs that separate the four rows.
- The four segments are clear: big spenders (few large orders), loyal regulars (19 orders), customers slipping away (220 days since their last order) and new customers (one or two small orders).
Step 3: Turn Segments Into Actions
| Segment | Customers | What they look like | Suggested action |
|---|---|---|---|
| Loyal regulars | 133 | Order often, recently | Loyalty points, early access to sales |
| Slipping away | 109 | No order for about 7 months | “We miss you” discount, short survey |
| New customers | 92 | One or two small, recent orders | Welcome series, second-order coupon |
| Big spenders | 66 | Few orders, very high value | Personal service, premium products |
Over a quarter of customers are slipping away. That is the clearest business finding: winning back even a few of them could be worth more than any other campaign.
Keep the segments fresh
Customers move between segments. A new customer may become loyal; a loyal one may drift away. Re-run the RFM step every month, and use the saved scaler and k-means model to assign each customer to a segment. The previous lesson shows how to save them.
Common Mistakes
- Clustering raw RFM values. Monetary is in thousands while frequency is in tens, so money alone would decide the clusters. Log and scale first.
- Trusting the silhouette score blindly. Also ask whether each segment is large enough and different enough to deserve its own plan.
- Leaving clusters as numbers. “Cluster 2” means nothing to a marketing team. Profile and name every segment.
- Using a fixed old date for recency. Measure recency from the day you run the analysis.
Practice Exercises
Exercise 1. Add a fourth column, average order value, to the RFM table. How do you compute it?
Show answer
rfm["avg_order"] = rfm["monetary"] / rfm["frequency"]
It separates big spenders (few large orders) from loyal regulars (many smaller orders) even more clearly. Remember to log and scale it with the others.
Exercise 2. The team wants a list of every “Slipping away” customer to email. How do you get it?
Show answer
names = profile["name"].to_dict() # segment number -> name
rfm["name"] = rfm["segment"].map(names)
emails = rfm[rfm["name"] == "Slipping away"].index.tolist()
The index of rfm holds the customer IDs, which you can join with the customer table to get email addresses.
Frequently Asked Questions
Can I do RFM segmentation without machine learning?
Yes. A common manual method gives each customer a score from 1 to 5 on each of R, F and M using quantiles, then groups score patterns such as 555 or 155. K-means finds the groups from the data instead of fixed cut-offs.
Which other clustering methods work for customer segmentation?
Gaussian mixture models give soft memberships, so a customer can be 70% one segment and 30% another. Hierarchical clustering shows how segments merge. DBSCAN finds odd customers as noise. K-means is the usual starting point because it is fast and easy to explain.
Summary
- RFM turns raw orders into recency, frequency and monetary value.
- Log and scale the columns before k-means.
- The silhouette score helps choose k; business sense makes the final call.
- Name each segment and give it a clear action.
Next: Gradient Boosting in Python.
