How do I build customer segments in Python with RFM and k means, and check that they are any good?
TL;DR
Difficulty: Intermediate
Segmentation in Python is two lines of k means and fifty lines of decisions around it. The decisions change the answer.
- Cluster on behaviour, profile on value, and keep one column back as a witness: the company field never went in, yet 89% of the corporate segment invoice a company.
- qcut fails on frequency because a third of customers have one order. Score with a percentile rank so equal customers keep equal scores.
- Scale the inputs, take logs of counts and shrink shares from one or two orders towards the average, or k means draws value bands and the silhouette rewards artefacts.
- In the generated Northgate data four segments emerge, and corporate senders, 7% of customers, bring 41% of the revenue. RFM scored 91% of them as one or two time buyers.
- Sign off on five numbers: silhouette 0.36, smallest segment 7.3%, worst random start 0.948, bootstrap median 0.991, agreement with a Gaussian mixture 97.1%.
RFM tells you who spent most recently and most often. It cannot tell a company buying for twelve offices from a sister buying for three sisters. This chapter builds the segmentation from my Marketing Analytics series in Python, on Northgate Hampers, the invented Leeds hamper shop from that chapter: from a raw order export to RFM scores, k means, a Gaussian mixture, stability checks and a model that scores next month.
What this chapter builds, and where the theory lives
The concepts are explained in Tools of segmentation: k means, latent class analysis and going beyond RFM, chapter 14 of my Marketing Analytics series: what a good segmentation has to deliver, why RFM ranks rather than describes, how k means and latent class analysis work, and how to check that segments are real. This chapter builds all of it in Python, line by line, on data you can generate and run yourself.
The example is the same one. Northgate Hampers is Priya's invented online hamper shop in Leeds, at northgatehampers.example, with 6,200 customers who ordered in the last 14 months. The theory chapter opens with two orders that landed within an hour of each other: an office manager sending twelve hampers to twelve offices, and a woman in Brighton sending three hampers to her three sisters. Priya's RFM scoring put both in the same cell, 515, and the automation sent both a "10% off your next hamper" email. One needed a phone call next October. The other needed a reminder before Mother's Day.
The data in this chapter is generated in code to resemble the example in the Marketing Analytics chapter. The generator builds in the same four kinds of customer, in the same proportions, so you will recognise the segments, their sizes and their share of revenue. The numbers come out of a simulation and carry its noise, so they differ from the theory chapter in the second digit, and I say where.
By the end you will have:
- one row per customer, built from a raw order export with test orders, staff orders and refunds in it
- RFM scores with
qcut, and the fix for the error everybody hits on the frequency column - k means with scikit learn, with scaled inputs, the elbow, the silhouette and many random starts
- a Gaussian mixture as the model based second opinion, with a probability of membership for every customer
- a profile of each segment from a
groupby, with names that come from the profile, not from a cluster number - five numbers that say whether the segments are any good, and a saved model that scores next month's customers.
You should be comfortable with pandas and with the group by and pivot tables chapter, because the customer table and every profile in this chapter are a groupby. If principal components and factor analysis in Python is fresh in your mind, good: the theory chapter clusters on component scores. Here I cluster on five behavioural columns directly, so that you can see every input, and I come back to components at the end.
Cluster on behaviour, profile on value, and keep a witness
If you take one idea from this chapter, take this one. The columns you cluster on and the columns you judge the result by must be different columns.
Cluster on behaviour: how often someone orders, how many hampers go into one order, whether they write gift messages, whether they need a code, whether they only appear in December. Profile on value: revenue, average order, share of the shop's money. If value goes into the clustering, value comes out of it, and you have rebuilt RFM with more steps, which the theory chapter warns about. Kept out, value becomes a finding.
Then keep one honest column back as a witness. At Northgate the witness is the company field on the invoice. It is not an input. If the clustering finds a group of corporate buyers purely from behaviour, the witness should confirm it, and if it does not, the segment is a story the algorithm told you.
Example: what the witness says at Northgate
The clustering below never sees the company field. It finds a segment of 455 customers who order rarely but put 13 hampers into the average order. When I profile that segment afterwards, 89% of them have a company name on the invoice, against 1% or less in every other segment. The algorithm found the corporate senders from behaviour alone, and a column it never saw agrees. That is the strongest single piece of evidence in this chapter that the segments live in the data, and it costs one line of code.
For the person who commissions this
If you will never run the code, here is what to ask for and what the answers mean.
A segmentation is worth paying for when it changes what the shop does for each group: a different channel, offer, timing or product. The theory chapter calls this actionability. Everything else is a quality check, and five numbers cover it:
| Check | What it answers | Pass mark I use | Northgate |
|---|---|---|---|
| Mean silhouette | Are customers closer to their own segment than to the next one? | above 0.25 | 0.36 |
| Smallest segment | Is every segment big enough to act on? | at least 5% of customers | 7.3% |
| Worst of 20 random starts | Does the answer depend on luck? | adjusted Rand index of 0.9 or more | 0.948 |
| Bootstrap median | Does the answer survive a different sample of customers? | adjusted Rand index of 0.7 or more | 0.991 |
| Second method | Does a different model find the same groups? | 75% or more agreement | 97.1% |
Ask for these five numbers, the profile table and one sentence per segment that the person running email could say without looking at a table. If any number misses, ask why before anyone builds an email flow on it. The pass marks for stability and agreement are the ones I set in the theory chapter. The silhouette mark comes from the original guidance on reading silhouettes, which calls anything at or below 0.25 "no substantial structure".1
For Northgate the answer is four segments, and the one that matters most is the smallest: 7% of customers bring 41% of the revenue, and RFM scored 91% of them as one or two time buyers.
Setting up: the versions this chapter uses
This chapter runs on Python 3.14 with pandas 3.0.4, NumPy 2.5.1, scikit learn 1.9.0 and SciPy 1.18.0, the current releases in early July 2026. Make a fresh environment so nothing older leaks in:
python3.14 -m venv .venv
source .venv/bin/activate
pip install "pandas==3.0.4" "numpy==2.5.1" "scikit-learn==1.9.0" "scipy==1.18.0" "joblib"
Two pandas 3.0 changes show up in this chapter.2 Text columns now load as the dedicated str type rather than the old object type, which you will see in dtypes. And copy on write is always on, so the defensive .copy() many tutorials put after a filter is no longer needed: a filtered frame behaves as a copy, and assigning a new column to it does not touch the original or raise the old SettingWithCopyWarning.
Example: checking that you run what you think you run
import sys, numpy, pandas, sklearn, scipy
print(sys.version.split()[0], pandas.__version__, numpy.__version__, sklearn.__version__, scipy.__version__)
# 3.14.x 3.0.4 2.5.1 1.9.0 1.18.0
If your numbers differ in the last digit, the code still runs. If pandas starts with a 2, the str type will show as object and nothing else in this chapter changes.
Generating Northgate's order export
The generator builds 6,200 customers in four hidden groups, with the sizes of the theory chapter: 2,424 occasion gifters (A), 447 corporate senders (B), 1,241 treat yourself regulars (C) and 2,088 bargain occasionals (D). Each group has its own habits. Then it writes the order export a real shop would give you, one row per order. Every block in this chapter runs in order in one notebook.
import numpy as np
import pandas as pd
rng = np.random.default_rng(14)
# 6,200 invented customers in four hidden groups
sizes = {"A": 2424, "B": 447, "C": 1241, "D": 2088}
true_seg = np.repeat(list(sizes), list(sizes.values()))
n = len(true_seg)
customer_id = np.arange(1001, 1001 + n)
# how each hidden group behaves in the 14 month window
behaviour = pd.DataFrame({
"orders": [2.8, 1.55, 8.0, 1.5], # mean orders in 14 months
"units": [1.6, 13.0, 1.15, 1.2], # mean hampers per order
"price": [39.0, 80.0, 43.0, 32.0], # mean price per hamper in pounds
"gift": [0.88, 0.87, 0.09, 0.57], # chance an order has a gift message
"company": [0.01, 0.91, 0.01, 0.00], # chance the customer invoices a company
"voucher": [0.20, 0.12, 0.31, 0.80], # chance an order uses a code
"december": [0.45, 0.79, 0.18, 0.35], # chance an order falls in December
}, index=list("ABCD"))
b = behaviour.loc[true_seg].reset_index(drop=True)
The hidden group (true_seg) is the answer key. A real shop never has it. Here it lets you check later whether the methods find what was built in, which is the main reason to practise on generated data before you touch your own.
The next block turns customers into orders. Each customer gets at least one order, December orders cluster in the first 24 days of December 2024 and December 2025, and every order arrives in the daytime.
# one row per order: repeat each customer by their number of orders
n_orders = 1 + rng.poisson(b["orders"] - 1)
idx = np.repeat(np.arange(n), n_orders)
m = len(idx)
o = b.iloc[idx].reset_index(drop=True)
in_december = rng.random(m) < o["december"]
day = np.where(
in_december,
pd.to_datetime(rng.choice(["2024-12-01", "2025-12-01"], m)) + pd.to_timedelta(rng.integers(0, 24, m), unit="D"),
pd.Timestamp("2024-11-01") + pd.to_timedelta(rng.integers(0, 426, m), unit="D"), # to 31 Dec 2025
)
hour = pd.to_timedelta(rng.uniform(8, 20, m), unit="h") # shop orders arrive in the daytime
units = 1 + rng.poisson(o["units"] - 1)
orders = pd.DataFrame({
"order_id": np.arange(500001, 500001 + m),
"customer_id": customer_id[idx],
"email": [f"customer{c}@mail.example" for c in customer_id[idx]],
"created_at": (pd.to_datetime(day) + hour).tz_localize("UTC"),
"type": "order",
"units": units,
"total": np.round(units * o["price"] * rng.lognormal(0, 0.18, m), 2),
"gift_message": rng.random(m) < o["gift"],
"voucher_code": rng.random(m) < o["voucher"],
"company": (rng.random(n) < b["company"].to_numpy())[idx],
})
Example: adding the traps a real export carries
A clean table like this does not exist in any shop I have seen. So the last generator block adds what the theory chapter's file would really contain: 3% of orders refunded, each refund as its own row with a negative total, and 60 internal orders, 35 test orders from the shop's own test address and 25 staff orders from Sam in the office.
# refunds as extra rows, test and staff orders on the shop's own domain
refunded = orders.sample(frac=0.03, random_state=1)
refunds = refunded.assign(type="refund", total=-refunded["total"], units=0,
created_at=refunded["created_at"] + pd.Timedelta(days=9))
internal = orders.sample(60, random_state=2).assign(
customer_id=[0] * 35 + [99] * 25,
email=["test@northgatehampers.example"] * 35 + ["sam@northgatehampers.example"] * 25,
order_id=np.arange(900001, 900061),
)
export = pd.concat([orders, refunds, internal]).sort_values("created_at", ignore_index=True)
print(export.shape)
print(export.dtypes)
# (21102, 10)
# order_id int64
# customer_id int64
# email str
# created_at datetime64[ns, UTC]
# type str
# units int64
# total float64
# gift_message bool
# voucher_code bool
# company bool
21,102 rows: 20,429 real orders, 613 refund rows and 60 internal orders. Note str for the two text columns, the pandas 3.0 string type, and the time stamps in UTC, as most shop exports deliver them.
From orders to one row per customer
Segmentation works on customers, not orders, so the first real step is a groupby. Three decisions come before it, and each one changes the segments.
Internal orders go. Test and staff orders are not customers. Customer 0 with 35 orders would become the most loyal regular in the shop. Filter on something that cannot be faked by a customer, here the shop's own email domain.
Refunds are money, not orders. A refund row must reduce spend but must not count as an order. Counting it would double the frequency of every customer who returned something.
December means December in the shop's time zone. The export is in UTC. Northgate's property and its customers live on UK time, so convert before you take the month. For a UK shop in winter the two agree, which is why nothing moves here, but a German or Austrian shop sits an hour ahead and a midnight order on 30 November would change month. Convert anyway, it costs one line and the habit protects every other analysis. Cleaning data in pandas and loading business data into pandas cover these traps in general.
clean = export[~export["email"].str.endswith("@northgatehampers.example")]
clean["local_time"] = clean["created_at"].dt.tz_convert("Europe/London")
clean["december"] = clean["local_time"].dt.month == 12
real = clean[clean["type"] == "order"]
customers = real.groupby("customer_id").agg(
orders=("order_id", "size"),
units=("units", "sum"),
gift_message_share=("gift_message", "mean"),
voucher_share=("voucher_code", "mean"),
december_share=("december", "mean"),
company_on_invoice=("company", "max"),
last_order=("local_time", "max"),
)
customers["spend"] = clean.groupby("customer_id")["total"].sum() # refunds netted off
customers["avg_order_value"] = customers["spend"] / customers["orders"]
customers["units_per_order"] = customers["units"] / customers["orders"]
as_of = pd.Timestamp("2026-01-01", tz="Europe/London")
customers["days_since_last"] = (as_of - customers["last_order"]).dt.days
customers["company_on_invoice"] = customers["company_on_invoice"].astype(int)
c = customers
print(len(c), round(c["spend"].sum()), round((c["orders"] == 1).mean(), 3))
# 6200 1719835 0.315
The named aggregation inside agg (orders=("order_id", "size")) gives every output column a readable name in one step. The mean of a True or False column is the share of True, so gift_message_share is the share of a customer's orders with a gift message. McKinney's chapter on aggregation explains both patterns.3
Example: what the customer table says
6,200 customers, £1,719,835 of revenue after refunds, and 31.5% of customers with exactly one order. The theory chapter's file had £1,770,862 and 34%, close enough that the story holds. 63 customers have a spend of zero or less because everything they bought came back. They stay in: they are real customers with real behaviour, and a segmentation that drops them silently will look better than it is.
The table is scored as of 1 January 2026, the day after the window closes, which is when Priya's December automation would read it.
RFM scores with qcut, and the error you will hit
RFM summarises the past in three numbers: recency (days since the last order), frequency (number of orders) and monetary value (the average order).4 Each is ranked into fifths, from 1 for the lowest fifth to 5 for the highest, and written side by side:
Here is the three digit code for customer , the recency score from 1 to 5 with 5 for the most recent fifth, the frequency score and the monetary score, each from 1 for the lowest fifth to 5 for the highest. Cutting a ranked list into fifths is the same operation as finding a median, only at four cut points instead of one, see Foundations: median and mode.
pandas has a function for exactly this, qcut, which cuts a column at its sample quantiles.5 Try it on frequency:
try:
pd.qcut(c["orders"], 5, labels=[1, 2, 3, 4, 5])
except ValueError as err:
print(err)
# Bin edges must be unique: Index([1.0, 1.0, 2.0, 3.0, 5.0, 17.0], dtype='float64', name='orders').
# You can drop duplicate edges by setting the 'duplicates' kwarg
The error is the data talking. 31.5% of customers have exactly one order, so the 0% and the 20% quantiles are both 1, and two fifths would share the same edge. Every shop has this, because frequency is a count with a pile at one.
The two fixes in most tutorials both hurt. duplicates="drop" silently gives you four groups instead of five, and then the labels no longer fit. Ranking first with rank(method="first") forces five equal groups by breaking ties in row order:
spread = pd.qcut(c["orders"].rank(method="first"), 5, labels=[1, 2, 3, 4, 5])
print(pd.crosstab(c["orders"].clip(upper=3), spread))
# col_0 1 2 3 4 5
# orders
# 1 1240 713 0 0 0
# 2 0 527 978 0 0
# 3 0 0 262 1240 1240
Look at the first row. 1,240 one order customers get F = 1 and 713 identical one order customers get F = 2, decided by nothing but where they sit in the file. Sort the file differently and customers change cell. That is not a score, it is a lottery.
Example: a score where equal customers stay equal
The rule I use: customers with the same value get the same score, and the fifths are allowed to be uneven. A percentile rank with method="min" gives every tied customer the lowest rank of their group, and multiplying by 5 and rounding up turns it into a score from 1 to 5.
def score(s):
"""1 for the lowest fifth, 5 for the highest; equal values share a score."""
return np.ceil(5 * s.rank(method="min", pct=True)).astype(int)
c["R"] = score(-c["days_since_last"]) # fewer days since the last order scores higher
c["F"] = score(c["orders"])
c["M"] = score(c["avg_order_value"])
c["RFM"] = 100 * c["R"] + 10 * c["F"] + c["M"]
print(c["F"].value_counts().sort_index().to_dict())
# {1: 1953, 2: 1505, 3: 831, 4: 807, 5: 1104}
Walk one customer through it. A one order customer has the lowest rank, so rank(method="min", pct=True) gives , and
Here means "round up to the next whole number" and is the percentile rank . A two order customer starts at rank 1,954, the first rank after the 1,953 one order customers, so the percentile rank is and . All 1,953 one order customers share F = 1, more than a fifth, exactly as in the theory chapter.
In this file the most recent fifth ordered within the last 13 days, because December dominates, and the top fifth by average order starts at £70.45 (the theory chapter: 46 days and £69.08).
Two customers, one cell
Now the opening of the theory chapter, in code. Here are two customers from the 515 cell:
cols = ["orders", "units", "spend", "R", "F", "M", "RFM", "company_on_invoice"]
print(c.loc[[3427, 1189], cols])
# orders units spend R F M RFM company_on_invoice
# customer_id
# 3427 1 16 1159.14 5 1 5 515 1
# 1189 1 3 107.43 5 1 5 515 0
Example: what the 515 cell really contains
Customer 3427 sent 16 hampers in one December order and invoiced a company, £1,159. Customer 1189 sent three hampers with gift messages, £107. Both ordered once, both in the last fortnight of December, both above £70.45 an order. RFM cannot tell them apart, because the one thing that differs, 16 hampers against three, is not in R, F or M.
cell = c[c["RFM"] == 515]
print(len(cell), cell["company_on_invoice"].sum())
# 57 29
57 customers share the cell, and 29 of them invoice a company. One "welcome, here is 10% off" email goes to all 57. The theory chapter found 49 in the cell, 40 of them corporate. The mix differs, the problem is the same: two businesses in one cell.
Why k means on raw columns rediscovers order value
k means places centre points, assigns every customer to the nearest centre, moves each centre to the mean of its customers, and repeats until nothing moves.6 It measures "nearest" with ordinary straight line distance, and that is where most first attempts go wrong.
Example: k means on unscaled columns
Feed it the raw columns, average order value in pounds next to shares between 0 and 1:
from sklearn.cluster import KMeans
raw = c[["orders", "avg_order_value", "gift_message_share", "voucher_share", "december_share"]]
naive = KMeans(n_clusters=4, n_init=10, random_state=1).fit(raw)
print(c.groupby(naive.labels_)["avg_order_value"].agg(["size", "min", "max"]).round(0))
# size min max
# 0 161 421.0 937.0
# 1 5766 0.0 347.0
# 2 197 949.0 1335.0
# 3 76 1345.0 2557.0
Four clusters, cut cleanly at about £420, £940 and £1,340 of average order. Three of them slice the corporate buyers by order size and the fourth holds 93% of the shop. A difference of £500 counts 500 times more than the difference between a customer who always writes a gift message and one who never does. The clustering ignored behaviour entirely and drew value bands, which is RFM's M column with more computing.
Building the inputs: logs, scaling and the one order problem
Three choices turn the customer table into inputs that k means can use honestly.
Logs for counts. Orders run from 1 to 17 and hampers per order from 1 to 25, with long right tails. The natural logarithm pulls the tail in, so that the step from one to two orders counts as much as the step from four to eight. That matches how the business thinks: a second order is a bigger event than a ninth.
Scaling. After the logs, every column is standardised:
Here is the scaled value of customer on input , the raw value, the mean of input over all customers and its standard deviation. After scaling, every input has mean 0 and standard deviation 1, so a distance of one unit means the same on every input. The mean and the standard deviation are explained in Foundations: the mean and Foundations: spread. scikit learn's StandardScaler does this, and putting it in a Pipeline with the clustering means the same scaling is reused when you score new customers, a pattern from statistical models in Python with statsmodels and scikit learn.
Shrinking shares from few orders. This is the trap I have not seen in a tutorial. A customer with one order has a gift message share of exactly 0 or exactly 1. One order is a coin toss, not a habit, yet the share says "always" or "never". 31.5% of Northgate's customers sit on those two values for every share, so the data has hard lumps that are artefacts of counting, and a clustering will happily draw its boundaries around the lumps.
The fix is old and simple: pull each share towards the shop average, more strongly the fewer orders it rests on.
Here is the shrunk share for customer , the raw share (for example the share of orders with a gift message), the customer's number of orders, the average share over all customers, and the weight of the average, counted in imaginary orders. It is a weighted mean of the customer's own share and the shop average, with weights and , see Foundations: the mean. I use : the shop average counts as two typical orders. A customer with 12 orders barely moves. A customer with one order moves two thirds of the way to the average.
Example: one gift message, shrunk by hand
The average gift message share at Northgate is 0.6156. A one order customer who wrote a gift message has and :
The same customer's voucher share of 0 becomes , and their December share of 1 becomes . "Always gifts, never uses a code, only December" becomes "leans gift, leans full price, leans December", which is all one order can honestly say.
def shrink(share, n_orders, weight=2):
"""Pull a share towards the shop average: one order says little."""
return (share * n_orders + share.mean() * weight) / (n_orders + weight)
X = pd.DataFrame({
"orders_log": np.log(c["orders"]),
"units_per_order_log": np.log(c["units_per_order"]),
"gift": shrink(c["gift_message_share"], c["orders"]),
"voucher": shrink(c["voucher_share"], c["orders"]),
"december": shrink(c["december_share"], c["orders"]),
})
print(X.loc[[3427, 1189]].round(2))
# orders_log units_per_order_log gift voucher december
# customer_id
# 3427 0.0 2.77 0.74 0.28 0.65
# 1189 0.0 1.10 0.74 0.28 0.65
The two customers from the 515 cell now differ in exactly one input, hampers per order, which is the only thing that really differs between them. Neither revenue nor average order value is an input, and the company field stays out as the witness.
How k means works, checked against the theory chapter
The algorithm minimises the total squared distance between every customer and the centre of their own cluster:6
Here is the within cluster sum of squares (WCSS), the number of clusters, the set of customers in cluster , the row of scaled inputs for customer , the centre of cluster , which is the mean of its customers, and the squared straight line distance between them. It is the sum of squared deviations behind the variance, only measured around each cluster's own mean, see Foundations: spread. scikit learn reports as inertia_.
The algorithm only finds a local minimum, and which one depends on where the centres start.6 That is why n_init matters, and why the default deserves suspicion: since scikit learn 1.4 the default is n_init="auto", which with the default k means++ start means a single run.7
Example: the theory chapter's six customers, in scikit learn
The theory chapter clusters six customers by hand, with a deliberately poor start on P1 and P3, and ends at after one customer switches. The same in code, passing the poor start as init:
P = np.array([[2, -1], [3, -1], [2, 0], [-1, 2], [0, 2], [-1, 1]], dtype=float)
six = KMeans(n_clusters=2, init=P[[0, 2]], n_init=1).fit(P)
print(six.labels_, six.cluster_centers_.round(2).tolist(), round(six.inertia_, 2))
# [0 0 0 1 1 1] [[2.33, -0.67], [-0.67, 1.67]] 2.67
The same centres, (2.33, minus 0.67) and (minus 0.67, 1.67), and the same . P3 moved to the first cluster, exactly as in the hand calculation. When the library and the hand calculation agree on a toy example, you know you are reading its output the right way before you point it at 6,200 customers.
Choosing k: the elbow and the silhouette
There is no correct in the data. There is a the data supports and the business can act on, and you want both. Two measures help with the first.
The elbow plots for each and looks for the point where an extra cluster stops buying much. The silhouette compares, for every customer, how close they sit to their own cluster with how close they sit to the nearest other one:8
Here is the silhouette of customer , the mean distance from customer to the other members of their own cluster, the mean distance to the members of the nearest other cluster, and the larger of the two, which keeps between minus 1 and 1. Near 1 means well placed, near 0 means on a boundary, below 0 means probably in the wrong cluster. The mean of over all customers is one ordinary average per , see Foundations: the mean.
Example: the theory chapter's silhouettes, checked
The theory chapter works out the silhouette of P3 by hand as 0.62 and states P1's as 0.74. silhouette_samples gives one value per point:
from sklearn.metrics import silhouette_samples
print(silhouette_samples(P, six.labels_).round(2))
# [0.74 0.74 0.62 0.77 0.66 0.68]
P1 at 0.74, P3 at 0.62, as by hand.
Example: k from 1 to 8 on Northgate
Now the real run: scaling and k means in one pipeline, from 1 to 8, 50 random starts each.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score
rows = []
for k in range(1, 9):
model = make_pipeline(StandardScaler(), KMeans(n_clusters=k, n_init=50, random_state=1)).fit(X)
labels = model[-1].labels_
rows.append({
"k": k,
"wcss": round(model[-1].inertia_),
"silhouette": silhouette_score(model[0].transform(X), labels) if k > 1 else np.nan,
"smallest": np.bincount(labels).min(),
})
print(pd.DataFrame(rows).round(2).to_string(index=False))
| k | WCSS | Mean silhouette | Smallest cluster |
|---|---|---|---|
| 1 | 31,000 | none | 6,200 |
| 2 | 22,273 | 0.32 | 1,320 |
| 3 | 16,486 | 0.32 | 1,259 |
| 4 | 12,207 | 0.36 | 455 |
| 5 | 10,439 | 0.35 | 454 |
| 6 | 9,086 | 0.33 | 453 |
| 7 | 8,347 | 0.34 | 449 |
| 8 | 7,796 | 0.35 | 449 |
The WCSS at is 31,000, which is no accident: five scaled inputs with variance 1 each over 6,200 customers.
The horizontal axis is the number of clusters, the vertical axis the within cluster sum of squares. Each of the first three extra clusters removes between about 4,300 and 8,700. The fifth removes 1,768, and every one after it less. The elbow sits at four. The silhouette peaks at four too, at 0.36, and four is the first at which the corporate senders get a cluster of their own, 455 customers, 7%.
The silhouette of 0.36 is honest and modest. The original guidance reads 0.26 to 0.50 as a weak structure that could be artificial and asks for additional checks,1 which is exactly what the rest of this chapter does. Real customer data rarely does better: people do not come in neat balls.
Example: what shrinking the shares did to the choice of k
Run the same loop with the raw shares instead of the shrunk ones, and the silhouette tells a different story:
X_raw = X.assign(gift=c["gift_message_share"], voucher=c["voucher_share"],
december=c["december_share"])
for k in range(2, 9):
model = make_pipeline(StandardScaler(), KMeans(n_clusters=k, n_init=50, random_state=1)).fit(X_raw)
print(k, round(silhouette_score(model[0].transform(X_raw), model[-1].labels_), 3))
# 2 0.247
# 3 0.304
# 4 0.35
# 5 0.374
# 6 0.35
# 7 0.378
# 8 0.39
The horizontal axis is the number of clusters, the vertical axis the mean silhouette for each version of the inputs. With raw shares the silhouette climbs all the way to eight clusters. The extra clusters are not new kinds of customer. They are the lumps: one order customers with a share of exactly 0 or exactly 1, neatly separated from everyone else and from each other. A silhouette rewards tight lumps, whatever made them. Shrinking removes the artefact, and the measure points back at the four groups that were actually built into the data.
Profiling the segments with groupby
Fit the chosen model once, keep it, and attach the cluster to every customer:
kmeans = make_pipeline(StandardScaler(), KMeans(n_clusters=4, n_init=50, random_state=1)).fit(X)
c["cluster"] = kmeans[-1].labels_
print(pd.DataFrame(kmeans[-1].cluster_centers_, columns=X.columns).round(2))
# orders_log units_per_order_log gift voucher december
# 0 -0.68 -0.39 0.05 1.21 -0.00
# 1 -0.72 3.19 0.55 -0.54 0.87
# 2 1.46 -0.43 -1.57 -0.35 -0.79
# 3 -0.07 -0.06 0.64 -0.66 0.23
Centres in standard units are for the analyst. Cluster 1 sits 3.19 standard deviations above average on hampers per order, cluster 0 1.21 above average on codes. The business needs the raw columns, averaged per segment, and that is a groupby:
g = c.groupby("cluster")
profile = pd.DataFrame({
"customers": g.size(),
"share": g.size() / len(c),
"orders_per_year": g["orders"].mean() * 12 / 14,
"units_per_order": g["units"].sum() / g["orders"].sum(),
"average_order": g["spend"].sum() / g["orders"].sum(),
"gift_message": g["gift_message_share"].mean(),
"voucher": g["voucher_share"].mean(),
"december": g["december_share"].mean(),
"company_invoice": g["company_on_invoice"].mean(),
"revenue_share": g["spend"].sum() / c["spend"].sum(),
})
Two details. The average order is total spend over total orders per segment, not the mean of each customer's average, so one customer with one huge order does not count as much as one with ten normal ones. And orders per year scales the 14 month window to 12.
Example: naming clusters from their profile, never from their number
Cluster numbers are arbitrary. Refit with another seed and cluster 1 may become cluster 3, and every report that says "cluster 1" silently means someone else. So the names come from the profile, by rule:
def name_segments(p):
"""Name clusters from their profile, never from their index."""
p = p.copy()
names = {}
for name, column in [("B Corporate senders", "units_per_order"),
("C Treat yourself regulars", "orders_per_year"),
("D Bargain occasionals", "voucher")]:
top = p[column].idxmax()
names[top] = name
p = p.drop(top)
names[p.index[0]] = "A Occasion gifters"
return names
names = name_segments(profile)
c["segment"] = c["cluster"].map(names)
profile = profile.rename(index=names).sort_index()
print(profile.round(2).T.to_string())
| Segment | Customers | Share | Orders per year | Hampers per order | Average order | Gift message | Code used | December | Company on invoice | Revenue share |
|---|---|---|---|---|---|---|---|---|---|---|
| A Occasion gifters | 2,538 | 41% | 2.3 | 1.56 | £59 | 85% | 13% | 54% | 1% | 23% |
| B Corporate senders | 455 | 7% | 1.3 | 13.04 | £1,021 | 88% | 13% | 83% | 89% | 41% |
| C Treat yourself regulars | 1,251 | 20% | 6.8 | 1.15 | £49 | 9% | 31% | 29% | 1% | 28% |
| D Bargain occasionals | 1,956 | 32% | 1.4 | 1.24 | £41 | 58% | 93% | 45% | 0% | 7% |
Gift message, code used and December are the average share of each customer's orders, company on invoice the share of customers. The December share runs higher than the theory chapter's because this window holds two Decembers.
The theory chapter's profile reads the same way: A at 39% of customers and 24% of revenue, B at 7% and 41%, C at 20% and 28%, D at 34% and 7%. The generated data lands within two points on every share.
The horizontal axis shows the four segments, the vertical axis each segment's share of customers and of revenue. Segment B is the smallest by headcount and the largest by revenue: £711,900 of £1,719,835 from 697 orders. Segment D is a third of the customers and 7% of the money. Grouped bars side by side are the honest form for a comparison like this, as showing amounts and proportions explains: two pies would hide the one thing that matters, the swap between headcount and revenue.
And the witness: 89% of segment B invoice a company. No other segment exceeds 1%. The clustering found the corporate buyers without ever being told who they were.
What RFM saw, and what the segments see
The segments do not replace RFM, they explain it. A crosstab of segment against frequency score shows where RFM goes wrong:
print(pd.crosstab(c["segment"], c["F"], normalize="index").round(2))
# F 1 2 3 4 5
# segment
# A Occasion gifters 0.23 0.28 0.23 0.22 0.03
# B Corporate senders 0.58 0.33 0.06 0.03 0.00
# C Treat yourself regulars 0.00 0.01 0.02 0.15 0.82
# D Bargain occasionals 0.56 0.32 0.09 0.02 0.00
print(c.loc[c["RFM"] == 515, "segment"].value_counts())
# B Corporate senders 33
# A Occasion gifters 15
# D Bargain occasionals 9
Example: the two customers from the opening
91% of segment B, 58% plus 33%, score F = 1 or 2, the same frequency profile as segment D. On a frequency ranking the most valuable relationships in the shop look like the bargain hunters. The theory chapter found 90%.
The 515 cell splits three ways: 33 corporate senders, 15 occasion gifters and nine bargain occasionals. Customer 3427 lands in B, customer 1189 in A. RFM sent both 10% off. The segments say: phone 3427 in October and ask how many offices this year, and remind 1189 three weeks before Mother's Day. Neither needed a discount.
A Gaussian mixture as the second opinion
k means gives hard membership: every customer is in exactly one segment. The theory chapter's second opinion is latent class analysis, which works on yes or no answers and gives every customer a probability per class. Its closest relative in scikit learn is the Gaussian mixture, which does the same for continuous inputs.9 It assumes that the customers come from groups, each a bell shaped cloud with its own centre and its own shape:
Here is the density of customer 's inputs, the number of components, the share of customers in component , and the normal density with centre and covariance matrix , which sets the spread and tilt of the cloud. Adding over the components for "either" and weighting by their shares is the law of total probability, see Foundations: probability. The probability that customer belongs to component follows from Bayes' rule:
Here is the posterior probability of component for customer , the numerator is the share of component times the density of the customer's inputs within it, and the denominator adds the same over every component , so that the probabilities for one customer sum to 1. This is the same structure as the theory chapter's latent class posterior, with normal densities in place of answer probabilities, see Foundations: probability.
The number of components is chosen with the Bayesian information criterion, the lowest BIC wins:10
Here is the natural logarithm of the maximised likelihood, the number of free parameters and the number of customers. The first term rewards fit, the second charges for every parameter. The likelihood is a product of probabilities, see Foundations: probability.
Example: the BIC that never stops falling
Fit mixtures with 1 to 8 components on the same scaled inputs and print the BIC:
from sklearn.mixture import GaussianMixture
scaled = kmeans[0].transform(X) # the same scaled inputs as k means
print(pd.DataFrame(scaled).duplicated().sum())
# 4431
for floor in [1e-6, 0.2]:
bic = {}
for k in range(1, 9):
gm = GaussianMixture(n_components=k, covariance_type="full", reg_covar=floor,
n_init=10, random_state=1).fit(scaled)
bic[k] = round(gm.bic(scaled))
print(floor, bic)
# 1e-06 {1: 83542, 2: 71928, 3: 69019, 4: 31862, 5: 34584, 6: 27535, 7: 6490, 8: 3944}
# 0.2 {1: 84458, 2: 77191, 3: 73439, 4: 72313, 5: 72354, 6: 72364, 7: 72448, 8: 72217}
With the default settings (the first line) the BIC jumps about and keeps falling to eight components. The first print explains why: 4,431 of the 6,200 rows are exact copies of another row. Every one order customer who ordered one hamper with a gift message, no code, in December, has the same five numbers. A Gaussian component can shrink onto such a stack of identical points, its spread approaching zero and its likelihood approaching infinity, a known weakness of mixture likelihoods.11 The BIC reads that as a superb fit and buys more components. Even on smooth data the BIC of a mixture tends to choose more components than there are groups, because it measures how well the mixture describes the shape of the data, not how many kinds of customer there are.12
The second line puts a floor under the spread. reg_covar adds a constant to the diagonal of every covariance matrix,9 and on scaled data 0.2 says: no group is tighter than about 0.45 standard deviations on any input. With the floor the BIC falls steeply to four components, 72,313, and then stays flat within 0.2% all the way to eight. Four groups carry the structure, and further components only describe shape.
Work one BIC through. A four component mixture with full covariance in five inputs has three free shares, centre values and covariance values, 83 parameters. The maximised log likelihood is and , so
which gm.bic rounds to , the value for four components in the second line above.
Example: how far the two methods agree
Fit the four component mixture, take each customer's most likely component, and compare it with the k means segments. The component numbers are as arbitrary as the cluster numbers, so match them on content, with the Hungarian method that SciPy provides as linear_sum_assignment.13
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import adjusted_rand_score
gmm = GaussianMixture(n_components=4, covariance_type="full", reg_covar=0.2,
n_init=10, random_state=1).fit(scaled)
post = gmm.predict_proba(scaled) # one probability per customer and component
table = pd.crosstab(c["segment"], post.argmax(axis=1))
rows, cols = linear_sum_assignment(-table.to_numpy()) # best one to one match
agreement = table.to_numpy()[rows, cols].sum() / len(c)
print(table)
print(round(agreement, 3), round(adjusted_rand_score(c["cluster"], post.argmax(axis=1)), 3))
# col_0 0 1 2 3
# segment
# A Occasion gifters 3 0 2 2533
# B Corporate senders 0 449 0 6
# C Treat yourself regulars 11 0 1229 11
# D Bargain occasionals 1807 0 4 145
# 0.971 0.909
97.1% of customers land in the matching group, 6,018 of 6,200. Of the 182 who move, 145 move from D to A: bargain occasionals whom the mixture sees as gifters who used a code. The theory chapter's k means and latent class analysis agreed on 93.7%, with most movers between A and D as well. That boundary is real, and the next example shows where it runs.
Example: the customers the model is unsure about
The mixture's real gift is the probability. Here is how confident it is about each customer:
c["gmm_segment"] = pd.Series(post.argmax(axis=1), index=c.index).map(
{cols[i]: table.index[rows[i]] for i in range(len(rows))})
c["confidence"] = post.max(axis=1)
bands = pd.cut(c["confidence"], [0, 0.7, 0.9, 1.0], labels=["0.7 or less", "0.7 to 0.9", "above 0.9"])
print(bands.value_counts().sort_index())
# 0.7 or less 390
# 0.7 to 0.9 540
# above 0.9 5270
unsure = c[c["confidence"] <= 0.7]
print(unsure.groupby("segment").size())
# A Occasion gifters 98
# B Corporate senders 2
# C Treat yourself regulars 33
# D Bargain occasionals 257
85% of customers are placed with a probability above 0.9. 390 customers, 6.3%, sit at 0.7 or below, and 355 of them are in A or D. These are the gift buyers who sometimes use a code, the people the segment names fit least. They are also the most useful list in the whole chapter for a test: send half of them a full price product story instead of a code and measure, the test the theory chapter proposes for segment D. How to run and read such a test is the subject of the next chapter in this series, A/B tests in Python.
Stability: random starts and resampled customers
A segmentation you cannot reproduce is not a segmentation. Two checks, both with the adjusted Rand index (ARI), which compares two groupings of the same customers: 1 means identical, values near 0 mean no more agreement than chance, and the numbering of the groups does not matter.14
Example: what a single random start costs
First, does the answer depend on where the centres start? Compare 20 runs with one start each against 20 runs with ten starts each:
ref = c["cluster"].to_numpy()
single = [adjusted_rand_score(ref, KMeans(n_clusters=4, n_init=1, random_state=s).fit(scaled).labels_)
for s in range(20)]
many = [adjusted_rand_score(ref, KMeans(n_clusters=4, n_init=10, random_state=s).fit(scaled).labels_)
for s in range(20)]
print(round(min(single), 2), sum(a < 0.9 for a in single), round(min(many), 3))
# 0.44 5 0.948
With one start, the worst run agrees with the reference at 0.44, and five of 20 runs fall below 0.9. That is the default in scikit learn today. One run in four would hand you a different segmentation, and nothing in the output warns you. With ten starts, the worst of 20 runs agrees at 0.948. Always set n_init yourself.
Example: resampling customers, four segments against five
Second, does the answer survive a different sample? The bootstrap resamples 6,200 customers with replacement, refits, scores every real customer with the refitted model and compares with the reference.15 The resampling idea is explained in Foundations: sampling.
def bootstrap_ari(X, k, ref, n_boot=100, seed=7):
"""Refit on resampled customers, score everyone, compare with the reference."""
rng_b = np.random.default_rng(seed)
out = []
for i in range(n_boot):
rows = rng_b.integers(0, len(X), len(X))
model = make_pipeline(StandardScaler(), KMeans(n_clusters=k, n_init=10, random_state=i))
out.append(adjusted_rand_score(ref, model.fit(X.iloc[rows]).predict(X)))
return np.median(out), np.percentile(out, 5)
ref5 = make_pipeline(StandardScaler(), KMeans(n_clusters=5, n_init=50, random_state=1)).fit(X)[-1].labels_
for k, r in [(4, ref), (5, ref5)]:
med, p5 = bootstrap_ari(X, k, r)
print(k, round(med, 3), round(p5, 3))
# 4 0.991 0.947
# 5 0.873 0.514
The horizontal axis shows the two solutions, the vertical axis the adjusted Rand index against the reference. Four segments come back almost identically from every resample: median 0.991, and even the weakest 5% of refits at 0.947. Five segments look fine at the median, 0.873, but the weakest 5% fall to 0.514. The fifth segment exists in some samples and not in others. On the silhouette, four and five were 0.36 against 0.35, too close to call. Stability calls it.
Five numbers before you sign off
The checks above fit in one small function. It is the table from the section for the person who commissions this, in code:
def sign_off(silhouette, smallest_share, worst_seed, boot_median, agreement):
checks = {
"silhouette above 0.25": silhouette > 0.25,
"smallest segment at least 5% of customers": smallest_share >= 0.05,
"worst of 20 seeds, adjusted Rand at least 0.9": worst_seed >= 0.9,
"bootstrap median adjusted Rand at least 0.7": boot_median >= 0.7,
"second method agrees on at least 75%": agreement >= 0.75,
}
return pd.Series(checks)
med4, p5_4 = bootstrap_ari(X, 4, ref)
print(sign_off(0.36, profile["share"].min(), min(many), med4, agreement))
# silhouette above 0.25 True
# smallest segment at least 5% of customers True
# worst of 20 seeds, adjusted Rand at least 0.9 True
# bootstrap median adjusted Rand at least 0.7 True
# second method agrees on at least 75% True
Example: reading the five together
No single number proves anything. The silhouette of 0.36 alone says "weak, possibly artificial". The stability numbers alone say "reproducible", but a reproducible artefact is still an artefact. Together, with the witness column on top, they say: four groups, found the same way from every start and every sample, found again by a different model, and confirmed by a column the clustering never saw. That is as much certainty as customer data gives. The two judgements no code can make stay with the business: can someone describe each segment in a sentence, and will the shop do something different for each one.
Scoring next month without refitting
The fitted pipeline holds the scaler's means and standard deviations and the four centres. Save it, with the names, and score each month's customer table with it. Saving and reloading models as files is part of a reproducible Python analysis workflow.
import joblib
joblib.dump({"model": kmeans, "names": names}, "segments_2026_01.joblib")
saved = joblib.load("segments_2026_01.joblib")
new_month = X.sample(5, random_state=3) # stand in for next month's customer table
scored = pd.DataFrame({
"segment": pd.Series(saved["model"].predict(new_month), index=new_month.index).map(saved["names"]),
"distance": saved["model"].transform(new_month).min(axis=1).round(2),
})
print(scored)
# segment distance
# customer_id
# 4156 C Treat yourself regulars 1.41
# 4636 C Treat yourself regulars 1.08
# 3423 A Occasion gifters 1.17
# 3425 B Corporate senders 1.02
# 2585 A Occasion gifters 0.75
print(round(np.percentile(kmeans.transform(X).min(axis=1), 99), 2))
# 2.32
predict assigns each customer to the nearest saved centre, transform gives the distance to every centre, and the smallest of those is how typical the customer is of their segment. On the fitting month 1% of customers sit more than 2.32 standard units from any centre. Flag those for a look by hand each month: they are new kinds of customer, data errors, or the first sign that the segments are ageing.
Example: rescore monthly, refit yearly
Rescore every month, so that customers move between segments as they change: a bargain occasional who buys three times at full price is now a gifter or a regular, and a healthy shop moves people from D to A and from A to B. Count those moves in a migration table, a crosstab of last month's segment against this month's.
Do not refit every month. A refit moves the centres, renames nothing reliably and breaks every campaign report that names a segment. Refit once or twice a year, as a small project: fit the new model, run the five checks, crosstab old segments against new, and only then switch. Save the inputs' code with the model, because the shrinking weight and the log transform are part of the model as much as the centres are.
Traps from real exports that tutorials skip
The generated export carried three traps. Real ones carry more.
| Trap | What it does to the segments | What to do |
|---|---|---|
| Test and staff orders | One fake super regular, plus a skewed shop average for every shrunk share | Filter on the shop's own domain or a staff flag before anything else |
| Refunds as separate rows | Frequency doubled for every customer who returned something | Net refunds into spend, count only real orders |
| Guest checkout | One person as several customer IDs, each with one order, so frequency and recency look worse | Group on a cleaned email address (lower case, trimmed) where the shop allows guest orders |
| Time stamps in UTC | December or a sale week shifts at the edges for shops east of London | Convert to the shop's time zone before taking months, days or hours |
| Company field filled by hand | The witness column becomes noise | Check its fill rate before you rely on it as a check |
| Many customers with identical rows | Mixtures collapse onto the stacks, the BIC keeps adding components | Count duplicates, shrink shares, put a floor under the spread |
| One order customers | Hard lumps at 0 and 1, the silhouette rewards extra clusters | Shrink shares towards the average |
Example: the guest checkout trap in numbers
Suppose 30% of Northgate's one order customers were really repeat buyers who checked out as guests with a new customer ID each time. Grouping by customer ID would leave them as one order customers, so the frequency score would put them in F = 1, the shrinking would pull their shares towards the average, and k means would push many of them into D. The segment D in the profile table would then hold loyal gift buyers who simply never made an account, and the "bargain" name would be wrong for them. The fix is one line before the groupby: build the key from email.str.strip().str.lower() rather than from the customer ID, and check how many IDs collapse into one person.
Segments are profiling: a short word on data protection
Grouping customers by their behaviour to decide what to send them is profiling under the UK GDPR, which defines profiling as automated processing of personal data to analyse or predict aspects such as a person's preferences, interests or behaviour.16 Two consequences matter for a shop. People have an absolute right to object to direct marketing, and that includes profiling to the extent it is related to such marketing.17 And the data should be limited to what the purpose needs: the inputs in this chapter are counts and shares from the order history, no addresses, no free text, no gift messages themselves. The Information Commissioner's Office explains profiling and the related rights in its guidance.18 This is general information, not legal advice.
Example: what goes into the customer table and what stays out
In: the number of orders, hampers per order, the share of orders with a gift message, with a code and in December, the company flag, spend. Out: the gift message text, delivery addresses, names. The segment field that goes into the email tool carries one letter per customer. A customer who objects to marketing is removed from the scored file before it leaves the analysis, not afterwards in the email tool.
My view
I would build every customer segmentation the way this chapter does, in this order: clean the export, write the purpose down, cluster on behaviour, profile on value, keep a witness, run a second method, and check stability before anyone names a segment in a meeting. The algorithm is the smallest part. In this chapter the code that runs k means is two lines. The code that decides what goes into it is fifty, and every one of those decisions changed the answer: unscaled inputs drew value bands, raw shares invented clusters, a single random start gave a different segmentation one time in four, and the default mixture settings found eight groups in a file with four.
On the choice of tools: k means first, because it is fast, transparent and easy to score, and a Gaussian mixture as the second opinion, because its probabilities show where the boundaries are soft. If your inputs are mostly yes or no answers, survey items or categories, follow the theory chapter to latent class analysis instead. If you have many correlated behavioural columns, reduce them to components first, as principal components and factor analysis in Python shows, and cluster on the scores.
And I would not trust a segmentation that has not been tested in the market. "Bargain occasionals" is a hypothesis about 1,956 people, generated from five numbers. The 390 customers the mixture is unsure about are the obvious first place to test it.
Customer segmentation, the analysis behind it and the dashboards that keep it alive are a core part of my Data Science work, on the shop's own data, which stays the shop's. If you want to see what this would look like on your order history, the free workshop is the place to start, and my prices are published in full.
Conclusion
Segmentation in Python is a short pipeline with long decisions in it. Build one row per customer from a cleaned export, net off refunds and remove internal orders. Score RFM with a percentile rank so that equal customers stay equal, and read it as a ranking of value, not a description of behaviour. Cluster on scaled behavioural inputs, with logs for counts and shrunk shares for customers with few orders, and keep value and one witness column out. Choose with the elbow, the silhouette and the smallest segment, then let stability decide between close calls. Profile with a groupby, name segments from the profile, and confirm with a Gaussian mixture whose spread has a floor.
At Northgate that pipeline finds four segments that match the theory chapter within two points on every share. The smallest, corporate senders at 7% of customers, brings 41% of the revenue, and RFM scored 91% of them as one or two time buyers. The five sign off numbers pass, the witness column agrees at 89%, and the 390 customers the model is unsure about are the first list to test. The concepts behind every step are in Tools of segmentation. What the segments are for, before any algorithm, is in Segmentation: strategy before algorithms, and what to do with them afterwards in the customer loyalty journey.
