👩‍💼
Real-world scenario
Aisha (Nairobi, fintech): Finding which 800 merchants to invest retention spend on

Aisha is a junior data analyst at an M-Pesa fintech startup in Nairobi. Her boss just said: "We want to roll out a retention campaign—loyalty rewards, win-back offers, the works. But budget is tight. Which merchants should we focus on?"

Aisha has 800 merchants, 90 days of transaction data (recency, frequency, spend), and one afternoon to segment them. She can't manually score each merchant. Instead, she uses RFM: compute a Recency score (low days = high score), Frequency score, and Monetary score, then combine them into segments. Champions get loyalty perks. At-Risk merchants get a discount. Hibernating merchants get skipped—too cold to warm up. In 30 minutes, she has a segmentation model and a slide showing which 97 Champions bring in 21% of total value.

800
Merchants
5
Towns
6
Segments
What you'll learn
  • Understand why all three (Recency, Frequency, Monetary) matter
  • Compute Recency from date columns: (today - date).dt.days
  • Score each metric with pd.qcut() to create quartiles
  • Combine scores into segment labels (Champions, Loyal, At Risk, etc.)
  • Visualize segment distribution and value concentration
  • Design action plans for each segment

What is RFM?

RFM segmentation divides your customers into groups based on three simple metrics:

  • Recency (R): How many days since their last transaction? Recent customers are more likely to buy again.
  • Frequency (F): How many transactions in the last 90 days? Frequent buyers are more loyal.
  • Monetary (M): Total spend in the last 90 days? High-value customers drive revenue.

Why all three? Because a one-time big spender is not the same as a loyal small buyer. A merchant who spent KSh 500k six months ago (low R, low F) is different from one who spent KSh 5k last week (high R, low M). RFM forces you to look at the full picture.

Key insight: A customer with R=1, F=4, M=3 (last purchased 90 days ago but used to be frequent) is "At Risk"—worth a win-back email. A customer with R=4, F=1, M=1 (just bought but rarely) is "Occasional"—no need to spend retention budget yet.

Computing Recency, Frequency, Monetary

Start with a CSV of transaction data: merchant ID, date, amount. Then compute the three metrics.

📁
M-Pesa merchant dataset included
Download mpesa_merchants.csv to follow along (800 merchants, 5 towns, realistic distributions).
Load and compute RFM raw metrics

The output shows the raw distributions—wide ranges, skewed (a few merchants with huge spend). Now visualize them.

Recency, Frequency, and Monetary distributions (800 merchants)
Histogram of Recency in days. Mean 36 days, median 24 days. Most merchants within 30 days, long tail to 250 days. Histogram of Frequency (90-day transactions). Mean 33 transactions, median 24. Log-normal shape. Histogram of Monetary (KSh). Mean ~100k, median ~56k. Highly right-skewed, few merchants with massive spend.
What this shows: Most merchants are active (60% within 30 days), but the tail reaches 250 days of inactivity. Frequency is log-normal: many small-frequency merchants, few very active ones. Monetary is even more skewed—a handful of merchants drive disproportionate value. This is typical fintech data: Pareto distribution.

Scoring with pd.qcut: quartile-based binning

Raw RFM metrics are hard to compare (recency is in days, frequency is a count, monetary is currency). pd.qcut() divides each metric into quartiles and assigns a score 1–4. Higher is better for all three (but recency is reverse-scored: low days = high score).

Score each RFM metric into quartiles

Why pd.qcut and not pd.cut? Because pd.qcut creates equal-count bins (each quartile has ~25% of rows), while pd.cut creates equal-width bins. In RFM, you want all four bins to have similar population so your segments are actionable and sized fairly.

Why reverse Recency? We want recency (days since last purchase) to feel like frequency: higher is better. So we flip it. A merchant who bought yesterday (0 days ago) gets R=4 (most recent, most valuable). A merchant who bought 200 days ago gets R=1 (stale, risky). This makes it intuitive: R=4, F=4, M=4 is a "Champion."

Combining scores into segment labels

Now that each merchant has an R, F, M score (each 1–4), combine them into business-meaningful segment labels.

Define segment rules and assign labels

Your segments now look like this:

Segment Count Avg Recency (days) Avg Frequency Avg Monetary (KSh) % of Total Value
Occasional 206 12 14 133,890 28.8%
At Risk 188 86 34 55,662 10.9%
Potential 110 11 50 28,445 3.3%
Inactive 107 81 10 120,733 13.5%
Champions 97 12 49 209,853 21.3%
Loyal 92 87 55 229,986 22.1%
What this shows: The 97 Champions (high R, F, M) generate 21% of total value despite being just 12% of the merchant base—classic Pareto. The 188 At Risk merchants (low R, decent F) are dangerous: they're fading. The 206 Occasional merchants are recent and moderate-spenders—low-hanging fruit for upsell. Loyal merchants haven't been active in 87 days but have high frequency and spend history—they're worth a "We miss you" campaign.

Visualizing segments: distribution and value concentration

Plots reveal actionable insights that numbers alone can't.

Frequency vs Monetary value, colored by Recency quartile
Scatter plot. X-axis: Frequency (90-day transactions). Y-axis: Monetary (KSh thousands). Points colored by Recency quartile. Recent merchants (R4, green) cluster near top-right. Old merchants (R1, red) scattered throughout.
What this shows: Recent merchants (green dots, R=4) sit near the top-right (high frequency, high value). Old merchants (red dots, R=1) are scattered—some are high-value sleepers worth reactivating, others are truly dead. The scatter pattern shows RFM is about three independent dimensions, not just sorting by one column.
Merchant count by RFM segment
Bar chart. Occasional (206) is tallest. Then At Risk (188), Potential (110), Inactive (107), Champions (97), Loyal (92).
What this shows: Your biggest segment is Occasional (206 merchants)—recent but low-frequency buyers. This is your growth lane: nurture them into repeat buyers. At Risk (188) is your second-biggest threat. Champions (97) are your core, but small. Budget your retention spend on At Risk first, then Occasional.
Total 90-day value contributed by each segment
Bar chart of total value. Occasional (KSh 27.6M) tops the chart. Loyal (KSh 21.2M) is second. Champions (KSh 20.4M) is third. At Risk contributes only KSh 10.5M.
What this shows: Despite Champions being your "best" segment, Occasional merchants generate slightly more total value (28.8% vs 21.3%) because there are more of them. Loyal merchants also punch above their weight—92 merchants, 87 days inactive, but 22% of total value. Protect them with a reactivation campaign. At Risk is the smallest generator, but also the riskiest—act fast.

Acting on segments: design retention campaigns

RFM scoring is worthless without action. Here's how to design retention campaigns for each segment:

Champions (97 merchants, 21% of value)

Strategy: Loyalty & VIP treatment. These merchants are your bread and butter.

  • Action: Loyalty rewards (fee rebates, priority support, early access to new features)
  • Frequency: Monthly engagement (newsletters, exclusive product launches)
  • Goal: Prevent churn; increase wallet share

Loyal (92 merchants, 22% of value)

Strategy: Reactivation. They used to be frequent; bring them back.

  • Action: "We miss you" email + 10% discount on next 5 transactions
  • Frequency: One-time burst campaign, then monitor
  • Goal: Re-engage lapsed high-value customers

Occasional (206 merchants, 29% of value)

Strategy: Growth. Recent, but low-frequency. Turn them into repeaters.

  • Action: Onboarding sequence (feature education, use-case guides)
  • Frequency: Bi-weekly tips + product announcements
  • Goal: Increase frequency (most impactful lever for this segment)

At Risk (188 merchants, 11% of value)

Strategy: Win-back. They're fading; act before they leave.

  • Action: Urgent discount (15–20%), survey about friction, priority support
  • Frequency: Urgent (today if possible)
  • Goal: Stop the bleed; understand why they've gone quiet

Potential (110 merchants, 3% of value)

Strategy: Monetization. Recent & frequent, but low spend. Upsell.

  • Action: Feature showcase (premium offerings, higher-value use cases)
  • Frequency: Monthly feature briefing
  • Goal: Increase average transaction size

Inactive (107 merchants, 14% of value)

Strategy: Retire (or deep reactivation). Low recency + low frequency. Not worth near-term spend.

  • Action: Archive or 1x per quarter "come back" email
  • Frequency: Quarterly at most
  • Goal: Minimize support cost; detect if they suddenly re-engage
0/ 3
Knowledge check: 3 questions
Q1: Why is Recency reverse-scored (low days = high score)?
Merchants who bought recently are more likely to buy again and are lower risk.
Because the metric is called "Recency," which means it must be backwards.
To match the scale of Frequency, which is also measured in days.
No reason; we just picked a random convention.
Q2: What is the main advantage of pd.qcut over pd.cut for RFM scoring?
pd.qcut creates equal-count bins (each quartile has ~25% of data), so all four RFM scores are fairly distributed.
pd.qcut is faster and more memory-efficient.
pd.cut doesn't work with monetary values over 1 million.
They are functionally identical; it doesn't matter which you use.
Q3: A merchant has R=4, F=4, M=1. Which segment do they belong to, and what's the action?
Potential: recent, frequent buyer, but low spend. Strategy: upsell them to higher-value offerings.
Champion: high recency and frequency, so they're a champion regardless of monetary value.
At Risk: low monetary value means they're not valuable and should be ignored.
Inactive: R=4 means they haven't been active for 4 months.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

Ready to go further?

Join the Best AI Program: The AI-Era Analyst — 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Analyst →