RFM Analysis in Python: Score and Segment Customers with pandas

Calculate recency, frequency and monetary value from an orders table, score each one from 1 to 5, label customer segments, and chart where the customers and the revenue are.

RFM analysis scores each customer on three numbers from an orders table: recency (days since the last order), frequency (number of orders) and monetary value (total spend). In pandas, aggregate with groupby("customer_id").agg(...), turn each column into a 1-5 score with pd.qcut, then name segments from the R and F scores.

Quick Example

This builds a fake orders table (10,110 orders from 3,000 customers), scores every customer, assigns a segment, and draws each segment's share of customers next to its share of revenue. Swap the first block for your own orders DataFrame with customer_id, order_date and amount columns.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# --- Sample orders: one row per order ---
rng = np.random.default_rng(64)
n = 3000
asof = pd.Timestamp("2026-11-30")
first = asof - pd.to_timedelta(rng.integers(0, 720, n), unit="D")  # each customer's first order
age = (asof - first).days.to_numpy()
active_days = np.minimum(rng.exponential(240, n), age)             # customers drift away over time
n_orders = 1 + rng.poisson(rng.gamma(1.2, 0.012, n) * active_days)
cust = np.repeat(np.arange(n), n_orders)
offset = rng.random(len(cust)) * active_days[cust]
offset[np.r_[0, np.cumsum(n_orders)[:-1]]] = 0                      # first order is on the first day
avg_order = rng.lognormal(3.8, 0.5, n)
orders = pd.DataFrame({
    "customer_id": cust,
    "order_date": (first[cust] + pd.to_timedelta(offset.astype(int), unit="D")).normalize(),
    "amount": (avg_order[cust] * rng.lognormal(0, 0.3, len(cust))).round(2),
})

# --- R, F and M per customer ---
snapshot = orders["order_date"].max() + pd.Timedelta(days=1)  # "today" for recency
rfm = orders.groupby("customer_id").agg(
    last_order=("order_date", "max"),
    frequency=("order_date", "size"),
    monetary=("amount", "sum"),
)
rfm["recency"] = (snapshot - rfm["last_order"]).dt.days

# --- Scores from 1 (worst) to 5 (best) ---
rfm["R"] = pd.qcut(rfm["recency"], 5, labels=[5, 4, 3, 2, 1]).astype(int)  # recent = high score
rfm["F"] = pd.cut(rfm["frequency"], [0, 1, 2, 4, 7, np.inf], labels=[1, 2, 3, 4, 5]).astype(int)
rfm["M"] = pd.qcut(rfm["monetary"], 5, labels=[1, 2, 3, 4, 5]).astype(int)

# --- Segments from R and F (first matching rule wins) ---
rfm["segment"] = np.select(
    [
        (rfm["R"] >= 4) & (rfm["F"] >= 4),   # buy often and just bought
        (rfm["R"] >= 3) & (rfm["F"] >= 3),   # buy often, recently enough
        (rfm["R"] >= 4) & (rfm["F"] == 1),   # first order, very recent
        (rfm["R"] >= 3),                     # recent, but only 1-2 orders
        (rfm["F"] >= 3),                     # used to buy often, gone quiet
    ],
    ["Champions", "Loyal", "New", "Promising", "At risk"],
    default="Hibernating",
)

# --- Share of customers vs share of revenue ---
by_segment = rfm.groupby("segment").agg(customers=("monetary", "size"), revenue=("monetary", "sum"))
shares = (by_segment / by_segment.sum() * 100).sort_values("revenue")

fig, ax = plt.subplots(figsize=(9, 5))
y = np.arange(len(shares))
ax.barh(y + 0.2, shares["customers"], height=0.38, color="#b9c0cc", label="% of customers")
ax.barh(y - 0.2, shares["revenue"], height=0.38, color="#7b3fa0", label="% of revenue")
ax.set_yticks(y, shares.index)
for i, (c, r) in enumerate(zip(shares["customers"], shares["revenue"])):
    ax.text(c + 0.5, i + 0.2, f"{c:.0f}%", va="center", fontsize=9)
    ax.text(r + 0.5, i - 0.2, f"{r:.0f}%", va="center", fontsize=9)
ax.set_xlabel("Share of total (%)")
ax.set_title("Customers vs revenue by RFM segment")
ax.legend(frameon=False, loc="lower right")
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Horizontal bar chart comparing each RFM segment's share of customers with its share of revenue: Champions are a small share of customers but the largest share of revenue, while Hibernating and New customers are a larger share of customers than of revenue

The gap between the two bars is the point of RFM. A segment with a longer revenue bar than customer bar carries more than its share of sales. A shorter one costs attention and brings back little.

How do you calculate recency, frequency and monetary value?

Pick a snapshot date (the day after your latest order, or the day you pulled the data), then group the orders by customer:

  • Recency is snapshot - last order date, in days. Smaller is better.
  • Frequency is the number of orders, here ("order_date", "size"). Use nunique on an order id if your table has one row per line item.
  • Monetary is the sum of amount. Use margin instead of revenue if you have it.
print(rfm[["recency", "frequency", "monetary", "R", "F", "M", "segment"]].head())
             recency  frequency  monetary  R  F  M      segment
customer_id                                                    
0                289          3    101.00  3  3  3        Loyal
1                680          1     27.67  1  1  1  Hibernating
2                532          3    105.73  1  3  3      At risk
3                267          4    286.06  3  3  5        Loyal
4                 51          3    110.20  5  3  3        Loyal

Recency is the only score where lower is better, so pd.qcut(..., labels=[5, 4, 3, 2, 1]) reverses the labels. Forgetting that is the most common RFM bug: the most recent customers end up with the lowest score.

Why does pd.qcut fail on frequency?

pd.qcut(rfm["frequency"], 5) splits customers into five equal-sized groups, but frequency is a small count with huge ties. Here 40% of customers have exactly one order, so several quantile edges land on 1 and pandas raises an error:

try:
    pd.qcut(rfm["frequency"], 5, labels=False)
except ValueError as e:
    print(e)
Bin edges must be unique: Index([1.0, 1.0, 1.0, 3.0, 5.0, 45.0], dtype='float64', name='frequency').
You can drop duplicate edges by setting the 'duplicates' kwarg

There are two fixes:

  • Fixed bins with pd.cut, as in the quick example: [0, 1, 2, 4, 7, np.inf] gives scores 1 to 5 for 1 order, 2 orders, 3-4, 5-7 and 8 or more. The groups are unequal, but the scores mean the same thing every month you rerun them.
  • Rank first: pd.qcut(rfm["frequency"].rank(method="first"), 5, labels=[1, 2, 3, 4, 5]). This forces equal groups, but it splits customers with identical order counts into different scores based on their row order, which is hard to defend.

Adding duplicates="drop" to qcut removes the first error, but you get fewer than five groups, and passing five labels then raises a second ValueError.

Which customers are in each segment?

Segment names are a lookup on R and F (M is usually left out of the names, because it correlates with F). The rules in np.select run in order, so the first matching one wins, and the last item, default="Hibernating", takes everyone left over. This table checks that the segments mean what their names say:

summary = rfm.groupby("segment").agg(
    customers=("monetary", "size"),
    median_recency_days=("recency", "median"),
    median_orders=("frequency", "median"),
    avg_spend=("monetary", "mean"),
    revenue=("monetary", "sum"),
)
summary["revenue_share"] = (summary["revenue"] / summary["revenue"].sum() * 100).round(1)
print(summary.drop(columns="revenue").round(0).sort_values("revenue_share", ascending=False).to_string())
             customers  median_recency_days  median_orders  avg_spend  revenue_share
segment                                                                             
Champions          376                 41.0            8.0      515.0           36.0
Loyal              476                162.0            4.0      259.0           23.0
At risk            372                422.0            4.0      271.0           19.0
Hibernating        828                498.0            1.0       69.0           11.0
Promising          569                189.0            2.0       82.0            9.0
New                379                 59.0            1.0       51.0            4.0

Tune the cutoffs to your business before you act on them. A subscription product might call 30 days of silence "at risk", and a furniture store might call it normal.

What does the R by F grid look like?

A heatmap of average spend for every R and F score pair shows the structure under the segment names, and it is a good way to check where you drew the segment borders:

import seaborn as sns

grid = rfm.pivot_table(index="R", columns="F", values="monetary", aggfunc="mean").sort_index(ascending=False)
counts = rfm.pivot_table(index="R", columns="F", values="monetary", aggfunc="size").sort_index(ascending=False)
annot = grid.round(0).astype("Int64").astype(str) + "\n(n=" + counts.fillna(0).astype(int).astype(str) + ")"

fig, ax = plt.subplots(figsize=(8, 5.5))
sns.heatmap(grid, annot=annot, fmt="", cmap="Purples", linewidths=1, linecolor="white",
            cbar_kws={"label": "Average spend per customer"}, ax=ax)
ax.set_xlabel("Frequency score (5 = most orders)")
ax.set_ylabel("Recency score (5 = most recent)")
ax.set_title("Average spend by recency and frequency score")
plt.show()

Heatmap of average customer spend for each recency score and frequency score, darkest in the top-right corner for recent frequent buyers and lightest for one-order customers, with the number of customers in each cell

Spend rises toward the top right, as it should. Cells with only a handful of customers (the n= in each cell) are noisy, so don't build a segment around one. Frequency drives spend more than recency in this data, because spend is a sum of orders.

How do the segments look on a scatter plot?

The scatter plot is a sanity check: the segments should form recognizable regions. Recency goes on the x-axis, frequency on a log y-axis, and each point is colored by segment. Because frequency is a whole number, jitter it a little so dots don't stack:

palette = {"Champions": "#7b3fa0", "Loyal": "#3a6ea5", "Promising": "#2a9d8f",
           "New": "#e9c46a", "At risk": "#e4572e", "Hibernating": "#9aa0a6"}

fig, ax = plt.subplots(figsize=(9, 5.5))
jitter = rng.uniform(0.9, 1.1, len(rfm))
for name, color in palette.items():
    part = rfm[rfm["segment"] == name]
    ax.scatter(part["recency"], part["frequency"] * jitter[part.index], s=10, alpha=0.5, color=color, label=name)

ax.set_yscale("log")
ax.set_xlabel("Recency (days since last order)")
ax.set_ylabel("Frequency (orders, log scale)")
ax.set_title("Customers by recency and frequency")
ax.legend(markerscale=2.5, frameon=False, ncols=2)
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Scatter plot of customers by recency in days on the x-axis and number of orders on a log y-axis, colored by RFM segment, with Champions at low recency and high frequency and Hibernating customers at high recency

part.index works as the jitter index because customer_id is a 0-based integer index here. If your IDs are strings, jitter with np.random.default_rng(1).uniform(0.9, 1.1, len(part)) inside the loop.

RFM, cohort retention, or survival curves?

Question Use
Which customers should I email, reward or win back right now? RFM segments
Did customers who joined after a product change stick around longer? Cohort retention heatmap
How long does a typical customer last, and do two plans differ? Kaplan-Meier survival curve

RFM is a snapshot: it describes customers as of one date and has no notion of time since signup. Rerun it monthly and track segment sizes if you want a trend.

Practical Tips

  • Fix the snapshot date. Using pd.Timestamp.today() makes your scores change every day you rerun the notebook. Use a fixed date, or the latest order date plus one day.
  • Check for refunds and test orders. Negative or zero amounts distort monetary quantiles. Filter them out before you aggregate.
  • Keep the scoring rules next to the segment rules. If you change [0, 1, 2, 4, 7, np.inf], rerun everything below it, since the segment names depend on the scores.
  • Look at the revenue bars before the names. Names like "Champions" are only a convention, and the share of revenue tells you whether the segment matters.
  • Don't confuse segments with customer value forecasts. RFM says what customers did. It doesn't estimate what they will spend next.

Similar Topics