Learn how to build a complete RFM customer segmentation pipeline in pandas — from raw transaction data to scored customers, named segments, and a formatted multi-tab Excel report. This expert-level lesson covers quintile binning, vectorized segment assignment, AOV calculation gotchas, and production-ready openpyxl formatting.

Imagine you're a data analyst at a mid-sized e-commerce company. Marketing wants to know which customers are worth investing in with a retention campaign, which are slipping away, and which are truly your best buyers. The database has 200,000 transaction rows and a list of roughly 18,000 unique customers. Your manager hands you a spreadsheet with some manual VLOOKUP-based categorizations from six months ago and says, "We need something like this, but automated, accurate, and updated every month."
This is exactly the problem that RFM analysis was designed to solve. RFM — Recency, Frequency, Monetary — is a proven behavioral segmentation framework borrowed from direct-mail marketing that quantifies customer value along three axes: how recently they bought, how often they buy, and how much they spend. It's rigorous enough to satisfy analysts and intuitive enough for marketers to act on. By the end of this lesson, you'll have a fully automated pandas pipeline that scores every customer, assigns them to named segments, computes segment-level KPIs, and exports a formatted multi-tab Excel workbook ready for stakeholders.
What you'll learn:
openpyxlYou should be comfortable with pandas DataFrames, groupby aggregations, and basic Python. If you need a refresher on groupby mechanics, Grouping and Aggregating in pandas: groupby as the PivotTable Replacement covers the foundation. If you're newer to pandas data types and date handling, Working with Dates and Time Series in pandas: Parsing, Resampling, and Rolling Windows will also be valuable context. This lesson uses pandas, numpy, openpyxl, and datetime — install them with pip install pandas numpy openpyxl if needed.
Before jumping into code, it's worth internalizing what RFM scores actually mean — because misunderstanding the scoring direction is the single most common source of bugs in RFM pipelines.
Recency is the number of days since a customer last made a purchase. A low recency value means the customer bought recently, which is good. This creates a subtle inversion: when you score recency, the customer with the lowest recency days should get the highest score (5). Every time you implement this from scratch, you need to consciously flip the ranking direction for recency.
Frequency is the total number of distinct transactions a customer has made in the analysis window. Higher frequency = higher score. Straightforward.
Monetary is the total revenue attributed to that customer. Higher revenue = higher score. Also straightforward.
We use quintile binning to convert these raw metrics into scores from 1 to 5. Quintile binning means we rank all customers and split them into five equal-sized groups. This approach is preferred over fixed thresholds (like "anyone who spent more than $500 gets a 5") because it adapts automatically to your data distribution. If you're in a low-ticket business where $200 is a big order, quintile binning handles that the same way it handles a high-ticket SaaS business where $200 barely registers.
Key insight
Quintile scoring is relative, not absolute. A score of 5 means "top 20% of your customers on this metric." It tells you nothing about absolute dollar amounts, which is why the KPI summary layer — where you show actual revenue, actual order counts — is what gives the segments business meaning.
Once we have three individual scores (R, F, M each ranging 1–5), we combine them into a composite RFM string like "555" or "312" and then map those combinations to human-readable segment names: Champions, Loyal Customers, At Risk, Lost, etc.
For this lesson, we'll generate a realistic synthetic transaction dataset so you can run everything end-to-end without needing a database connection. The data mimics what you'd pull from an order management system — one row per order with a customer ID, order date, and order value.
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
np.random.seed(42)
# Configuration
N_CUSTOMERS = 2000
N_ORDERS = 40000
ANALYSIS_DATE = datetime(2024, 1, 1) # Snapshot date for recency calculation
# Generate customer IDs
customer_ids = [f"CUST_{i:05d}" for i in range(1, N_CUSTOMERS + 1)]
# Simulate varying purchase behavior:
# ~20% are heavy buyers, ~60% are moderate, ~20% are one-time/lapsed
weights = np.concatenate([
np.ones(400) * 5.0, # heavy buyers
np.ones(1200) * 2.0, # moderate
np.ones(400) * 0.3, # lapsed/one-time
])
weights /= weights.sum()
order_customer_ids = np.random.choice(customer_ids, size=N_ORDERS, p=weights)
# Generate order dates spanning 2 years, with heavy buyers buying more recently
order_dates = []
for cid in order_customer_ids:
idx = int(cid.split("_")[1]) - 1
if idx < 400: # heavy buyers: mostly recent
days_ago = np.random.randint(1, 180)
elif idx < 1600: # moderate: spread across the year
days_ago = np.random.randint(1, 365)
else: # lapsed: older purchases
days_ago = np.random.randint(180, 730)
order_dates.append(ANALYSIS_DATE - timedelta(days=int(days_ago)))
# Generate order values with realistic skew
order_values = np.random.lognormal(mean=4.2, sigma=0.8, size=N_ORDERS)
order_values = np.clip(order_values, 5, 2000).round(2)
orders_df = pd.DataFrame({
"order_id": [f"ORD_{i:06d}" for i in range(1, N_ORDERS + 1)],
"customer_id": order_customer_ids,
"order_date": order_dates,
"order_value": order_values
})
orders_df["order_date"] = pd.to_datetime(orders_df["order_date"])
print(f"Orders shape: {orders_df.shape}")
print(orders_df.head())
print(orders_df.dtypes)
Notice we're using a log-normal distribution for order values. This is intentional — real transaction data almost always follows a right-skewed distribution with a long tail of large orders. Using a uniform distribution would produce unrealistic test data and might mask edge cases in your binning logic.
Note
In a real project, you'd load this from a database or CSV file. If you're querying from a SQL database, Reading from SQL Databases into pandas with SQLAlchemy covers how to get transaction data into a DataFrame with the same structure we're using here.
Now we aggregate the transaction data to the customer level, computing one row per customer with their Recency, Frequency, and Monetary values.
# Compute RFM metrics at the customer level
rfm = orders_df.groupby("customer_id").agg(
last_order_date=("order_date", "max"),
frequency=("order_id", "count"),
monetary=("order_value", "sum")
).reset_index()
# Recency: days since last purchase relative to our analysis snapshot
rfm["recency"] = (ANALYSIS_DATE - rfm["last_order_date"]).dt.days
# Clean up: drop the intermediate date column
rfm = rfm.drop(columns=["last_order_date"])
# Round monetary for cleanliness
rfm["monetary"] = rfm["monetary"].round(2)
print(rfm.describe())
print(rfm.head(10))
The .agg() call is doing three things simultaneously: finding the most recent order date per customer, counting orders, and summing revenue. This is a named aggregation pattern — last_order_date=("order_date", "max") — which gives us clean, readable column names rather than the double-level columns you'd get from a dict-based aggregation. If this pattern is new to you, it's covered in depth in Weighted Averages, Percent of Total, and Custom Aggregations in pandas: Going Beyond sum and mean in groupby.
At this point, rfm.describe() should show you the distribution of raw metrics. Take a moment to look at this output — it tells you a lot about the shape of your customer base before you start scoring. How skewed is monetary? What's the max recency (your oldest, most lapsed customer)?
Here's where the scoring happens. We use pd.qcut() for quintile binning. The key difference between qcut and cut is that qcut creates equal-frequency bins (each bin has roughly the same number of customers), while cut creates equal-width intervals. For RFM, we always want qcut.
def score_rfm(df):
"""
Assign quintile scores (1-5) for Recency, Frequency, and Monetary.
Recency is inverted: lower days = better = higher score.
Frequency and Monetary: higher = better = higher score.
"""
df = df.copy()
# Recency: inverted scoring (1=worst/most lapsed, 5=best/most recent)
df["r_score"] = pd.qcut(
df["recency"],
q=5,
labels=[5, 4, 3, 2, 1], # Note the inversion here
duplicates="drop"
).astype(int)
# Frequency: standard scoring (1=lowest, 5=highest)
df["f_score"] = pd.qcut(
df["frequency"],
q=5,
labels=[1, 2, 3, 4, 5],
duplicates="drop"
).astype(int)
# Monetary: standard scoring (1=lowest, 5=highest)
df["m_score"] = pd.qcut(
df["monetary"],
q=5,
labels=[1, 2, 3, 4, 5],
duplicates="drop"
).astype(int)
return df
rfm_scored = score_rfm(rfm)
# Combine into a composite RFM string for segment mapping
rfm_scored["rfm_string"] = (
rfm_scored["r_score"].astype(str) +
rfm_scored["f_score"].astype(str) +
rfm_scored["m_score"].astype(str)
)
# Composite numerical score (useful for ranking)
rfm_scored["rfm_score"] = (
rfm_scored["r_score"] + rfm_scored["f_score"] + rfm_scored["m_score"]
)
print(rfm_scored[["customer_id", "recency", "frequency", "monetary",
"r_score", "f_score", "m_score", "rfm_string"]].head(15))
Warning
The duplicates="drop" parameter in pd.qcut() is essential. In real datasets, you'll frequently encounter ties in integer columns like frequency — many customers might all have exactly 1 order, making it impossible to split them cleanly into 5 bins. Without duplicates="drop", pandas will raise a ValueError. With it, pandas merges duplicate bin edges, potentially creating unequal bin sizes. After scoring, verify your score distributions with rfm_scored["f_score"].value_counts() to confirm no score is drastically over- or under-represented.
The rfm_string is a 3-character string like "543" where the first digit is R, second is F, third is M. We'll use this for segment mapping in the next step.
A raw score of "555" is analytically meaningful, but marketing teams need language like "Champions" and "At Risk" to build campaigns. We'll define a mapping from RFM patterns to segment names.
The challenge is that there are 125 possible RFM combinations (5×5×5), and you don't want to manually define all of them. The standard approach is to define rules based on score ranges and apply them in priority order.
def assign_segment(r, f, m):
"""
Assign a segment label based on individual RFM scores.
Rules are evaluated in priority order — first match wins.
"""
rfm_avg = (r + f + m) / 3
if r >= 4 and f >= 4 and m >= 4:
return "Champions"
elif r >= 3 and f >= 3 and m >= 3:
return "Loyal Customers"
elif r >= 4 and f <= 2:
return "New Customers"
elif r >= 4 and f >= 2 and m >= 2:
return "Promising"
elif r == 3 and f >= 3:
return "Need Attention"
elif r <= 2 and f >= 3 and m >= 3:
return "At Risk"
elif r <= 2 and f >= 4 and m >= 4:
return "Can't Lose Them"
elif r <= 2 and f <= 2 and m <= 2:
return "Lost"
elif r <= 1 and f <= 1:
return "Hibernating"
else:
return "About to Sleep"
rfm_scored["segment"] = rfm_scored.apply(
lambda row: assign_segment(row["r_score"], row["f_score"], row["m_score"]),
axis=1
)
# Check segment distribution
print(rfm_scored["segment"].value_counts())
print("\nSegment proportions:")
print(rfm_scored["segment"].value_counts(normalize=True).round(3))
Tip
The .apply() with axis=1 approach works fine at this scale, but if you're running this on 500,000+ customers, vectorizing the conditions with np.select() will be significantly faster. See Writing Fast pandas Code: Vectorization Instead of apply and Loops for how to convert this kind of row-by-row logic into vectorized operations.
Here's what a vectorized version of the same logic looks like, which is much faster:
import numpy as np
conditions = [
(rfm_scored["r_score"] >= 4) & (rfm_scored["f_score"] >= 4) & (rfm_scored["m_score"] >= 4),
(rfm_scored["r_score"] >= 3) & (rfm_scored["f_score"] >= 3) & (rfm_scored["m_score"] >= 3),
(rfm_scored["r_score"] >= 4) & (rfm_scored["f_score"] <= 2),
(rfm_scored["r_score"] >= 4) & (rfm_scored["f_score"] >= 2) & (rfm_scored["m_score"] >= 2),
(rfm_scored["r_score"] == 3) & (rfm_scored["f_score"] >= 3),
(rfm_scored["r_score"] <= 2) & (rfm_scored["f_score"] >= 3) & (rfm_scored["m_score"] >= 3),
(rfm_scored["r_score"] <= 2) & (rfm_scored["f_score"] >= 4) & (rfm_scored["m_score"] >= 4),
(rfm_scored["r_score"] <= 2) & (rfm_scored["f_score"] <= 2) & (rfm_scored["m_score"] <= 2),
(rfm_scored["r_score"] <= 1) & (rfm_scored["f_score"] <= 1),
]
choices = [
"Champions", "Loyal Customers", "New Customers", "Promising",
"Need Attention", "At Risk", "Can't Lose Them", "Lost", "Hibernating"
]
rfm_scored["segment"] = np.select(conditions, choices, default="About to Sleep")
This produces identical results but processes the conditions as array operations rather than row-by-row Python function calls — a critical difference at scale.
The individual customer scores are useful for targeting, but stakeholders need a rolled-up view: how many customers are in each segment, what's the revenue contribution, what's the typical order frequency? This is where the segment summary table earns its place.
# First: join RFM scores back to the original orders to get full transaction detail
customer_segments = rfm_scored[["customer_id", "segment", "r_score", "f_score",
"m_score", "rfm_score", "recency", "frequency",
"monetary"]]
# Segment-level KPI summary
segment_summary = customer_segments.groupby("segment").agg(
customer_count=("customer_id", "count"),
total_revenue=("monetary", "sum"),
avg_revenue_per_customer=("monetary", "mean"),
median_revenue=("monetary", "median"),
avg_frequency=("frequency", "mean"),
avg_recency_days=("recency", "mean"),
avg_rfm_score=("rfm_score", "mean"),
).reset_index()
# Percent of total customers and revenue
segment_summary["pct_of_customers"] = (
segment_summary["customer_count"] / segment_summary["customer_count"].sum() * 100
).round(1)
segment_summary["pct_of_revenue"] = (
segment_summary["total_revenue"] / segment_summary["total_revenue"].sum() * 100
).round(1)
# Average order value: total_revenue / (frequency * customer_count) is wrong.
# We want mean(monetary / frequency) per segment — computed at customer level first
customer_segments["avg_order_value"] = (
customer_segments["monetary"] / customer_segments["frequency"]
)
aov_by_segment = customer_segments.groupby("segment")["avg_order_value"].mean().reset_index()
aov_by_segment.columns = ["segment", "avg_order_value"]
segment_summary = segment_summary.merge(aov_by_segment, on="segment")
# Round numeric columns
numeric_cols = ["total_revenue", "avg_revenue_per_customer", "median_revenue",
"avg_frequency", "avg_recency_days", "avg_rfm_score", "avg_order_value"]
segment_summary[numeric_cols] = segment_summary[numeric_cols].round(2)
# Sort by total revenue descending
segment_summary = segment_summary.sort_values("total_revenue", ascending=False).reset_index(drop=True)
print(segment_summary.to_string())
Notice the comment about average order value. This is a subtle but important calculation error that shows up frequently. You might be tempted to do total_revenue / (avg_frequency * customer_count), but that's not the same as the average of each customer's individual AOV. The right approach is to compute AOV per customer first, then average those values within each segment. For more on this kind of weighted aggregation subtlety, Weighted Averages, Percent of Total, and Custom Aggregations in pandas: Going Beyond sum and mean in groupby goes deep.
Key insight
The gap between pct_of_customers and pct_of_revenue for Champions and Loyal Customers tells you your 80/20 story. Typically, 20% of customers drive 60-80% of revenue. If you don't see this pattern in real data, that's itself a signal worth investigating — maybe your segments aren't discriminating well, or your business model is unusually uniform.
Before exporting, it's helpful to include a score distribution breakdown so analysts can validate that the binning worked as expected. This is essentially a crosstab of RFM scores.
# Distribution of individual scores
r_dist = rfm_scored["r_score"].value_counts().sort_index().reset_index()
r_dist.columns = ["score", "recency_count"]
f_dist = rfm_scored["f_score"].value_counts().sort_index().reset_index()
f_dist.columns = ["score", "frequency_count"]
m_dist = rfm_scored["m_score"].value_counts().sort_index().reset_index()
m_dist.columns = ["score", "monetary_count"]
score_distribution = r_dist.merge(f_dist, on="score").merge(m_dist, on="score")
# Add percentages
total = len(rfm_scored)
score_distribution["recency_pct"] = (score_distribution["recency_count"] / total * 100).round(1)
score_distribution["frequency_pct"] = (score_distribution["frequency_count"] / total * 100).round(1)
score_distribution["monetary_pct"] = (score_distribution["monetary_count"] / total * 100).round(1)
print(score_distribution)
In theory, with perfect quintile binning, each score should contain exactly 20% of customers. In practice, integer ties (especially in frequency) cause some deviation. This table is your diagnostic. If score 1 for frequency contains 45% of customers, it means roughly half your customers bought only once — a business insight in itself, and an important caveat about segment reliability.
Good segmentation reports don't just describe — they prescribe. Add a recommended action sheet so the workbook is immediately useful to the marketing team without a separate briefing document.
segment_actions = pd.DataFrame({
"segment": [
"Champions", "Loyal Customers", "New Customers", "Promising",
"Need Attention", "At Risk", "Can't Lose Them", "Lost",
"Hibernating", "About to Sleep"
],
"description": [
"Bought recently, buy often, spend the most",
"Buy regularly with good recency and spending",
"Bought recently but infrequently",
"Recent buyers with average frequency and spend",
"Above average frequency but declining recency",
"Used to buy often but haven't recently",
"High value customers who are slipping away",
"Lowest scores across all dimensions",
"Low recency and frequency — nearly churned",
"Decent scores but showing signs of disengagement"
],
"recommended_action": [
"Reward them. Ask for reviews. Offer early access to new products.",
"Upsell higher-value products. Offer loyalty program enrollment.",
"Onboarding campaign. Introduce product range. Build the habit.",
"Targeted offers to increase purchase frequency.",
"Re-engagement email. Personalized recommendations.",
"Win-back campaign. Offer strong incentive. Conduct exit survey.",
"Aggressive retention campaign. Personal outreach for high-value accounts.",
"Re-activate or suppress. Low ROI — test with minimal spend only.",
"Minimal investment. Test a reactivation sequence.",
"Gentle nudge. Limited-time offer to trigger next purchase."
],
"priority": [
"High", "High", "Medium", "Medium",
"Medium", "High", "Critical", "Low",
"Low", "Medium"
]
})
# Merge with actual counts from segment_summary for context
actions_enriched = segment_actions.merge(
segment_summary[["segment", "customer_count", "pct_of_customers",
"total_revenue", "pct_of_revenue"]],
on="segment",
how="left"
)
print(actions_enriched[["segment", "priority", "customer_count", "pct_of_revenue"]].to_string())
Now we assemble all the pieces into a formatted Excel workbook. We'll use openpyxl as the write engine (it handles formatting), and we'll apply column widths, header styling, and number formats to each sheet. For a thorough grounding in openpyxl formatting patterns, Automating Excel Reports with pandas and openpyxl: Formatted Workbooks Without Manual Work is the companion reference.
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment, numbers
from openpyxl.utils import get_column_letter
OUTPUT_PATH = "rfm_customer_segmentation_report.xlsx"
# ── Helper: auto-fit column widths ──────────────────────────────────────────
def autofit_columns(ws, min_width=10, max_width=50):
for col in ws.columns:
max_len = max(
len(str(cell.value)) if cell.value is not None else 0
for cell in col
)
col_letter = get_column_letter(col[0].column)
ws.column_dimensions[col_letter].width = min(max(max_len + 2, min_width), max_width)
# ── Helper: style the header row ─────────────────────────────────────────────
def style_header(ws, header_fill_hex="1F4E79", font_color="FFFFFF"):
fill = PatternFill(start_color=header_fill_hex,
end_color=header_fill_hex,
fill_type="solid")
font = Font(bold=True, color=font_color, name="Calibri", size=11)
for cell in ws[1]:
cell.fill = fill
cell.font = font
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
ws.row_dimensions[1].height = 30
# ── Helper: apply alternating row shading ────────────────────────────────────
def zebra_stripe(ws, light_hex="EBF3FB"):
fill = PatternFill(start_color=light_hex, end_color=light_hex, fill_type="solid")
for i, row in enumerate(ws.iter_rows(min_row=2), start=2):
if i % 2 == 0:
for cell in row:
cell.fill = fill
# ── Write all sheets ─────────────────────────────────────────────────────────
with pd.ExcelWriter(OUTPUT_PATH, engine="openpyxl") as writer:
# Sheet 1: Segment Summary KPIs
segment_summary.to_excel(writer, sheet_name="Segment Summary", index=False)
# Sheet 2: Full Customer-Level RFM Scores
customer_segments_export = rfm_scored[[
"customer_id", "recency", "frequency", "monetary",
"r_score", "f_score", "m_score", "rfm_score", "rfm_string", "segment"
]].sort_values("rfm_score", ascending=False).reset_index(drop=True)
customer_segments_export.to_excel(writer, sheet_name="Customer Scores", index=False)
# Sheet 3: Score Distribution Validation
score_distribution.to_excel(writer, sheet_name="Score Distribution", index=False)
# Sheet 4: Recommended Actions
actions_enriched.to_excel(writer, sheet_name="Segment Actions", index=False)
# Sheet 5: Methodology Notes
methodology = pd.DataFrame({
"Parameter": [
"Analysis Date", "RFM Window", "Scoring Method",
"Number of Quintiles", "Recency Direction",
"Segment Logic", "Total Customers", "Total Revenue"
],
"Value": [
str(ANALYSIS_DATE.date()),
"All available transaction history",
"Quintile binning (qcut) — equal-frequency bins",
"5 (scores 1–5)",
"Inverted: lower days = higher score",
"Rule-based using np.select on individual scores",
str(len(rfm_scored)),
f"${rfm_scored['monetary'].sum():,.2f}"
],
"Notes": [
"Change this date to shift the recency reference point",
"Filter orders_df before running to adjust the window",
"Adapts automatically to data distribution",
"Change q= in pd.qcut() to use deciles (10) if preferred",
"Critical: do NOT use ascending labels for recency",
"Adjust thresholds in conditions list to fit your business",
"After deduplication and scoring",
"Sum of monetary column in rfm_scored"
]
})
methodology.to_excel(writer, sheet_name="Methodology", index=False)
# ── Post-write formatting using openpyxl directly ────────────────────────────
wb = load_workbook(OUTPUT_PATH)
SHEET_CONFIGS = {
"Segment Summary": {
"currency_cols": ["total_revenue", "avg_revenue_per_customer",
"median_revenue", "avg_order_value"],
"pct_cols": ["pct_of_customers", "pct_of_revenue"],
},
"Customer Scores": {
"currency_cols": ["monetary"],
"pct_cols": [],
},
"Score Distribution": {"currency_cols": [], "pct_cols": []},
"Segment Actions": {"currency_cols": ["total_revenue"], "pct_cols": ["pct_of_customers", "pct_of_revenue"]},
"Methodology": {"currency_cols": [], "pct_cols": []},
}
for sheet_name, config in SHEET_CONFIGS.items():
ws = wb[sheet_name]
style_header(ws)
autofit_columns(ws)
zebra_stripe(ws)
# Freeze the top row
ws.freeze_panes = "A2"
# Apply number formats based on column headers
header_row = [cell.value for cell in ws[1]]
for col_idx, col_name in enumerate(header_row, start=1):
col_letter = get_column_letter(col_idx)
if col_name in config.get("currency_cols", []):
for row in ws.iter_rows(min_row=2, min_col=col_idx, max_col=col_idx):
for cell in row:
cell.number_format = '$#,##0.00'
elif col_name in config.get("pct_cols", []):
for row in ws.iter_rows(min_row=2, min_col=col_idx, max_col=col_idx):
for cell in row:
cell.number_format = '0.0"%"'
# Apply conditional shading to Segment Summary based on revenue concentration
ws_summary = wb["Segment Summary"]
header_row = [cell.value for cell in ws_summary[1]]
pct_rev_col = header_row.index("pct_of_revenue") + 1 # 1-indexed
high_fill = PatternFill(start_color="C6EFCE", end_color="C6EFCE", fill_type="solid")
med_fill = PatternFill(start_color="FFEB9C", end_color="FFEB9C", fill_type="solid")
low_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
for row in ws_summary.iter_rows(min_row=2, min_col=pct_rev_col, max_col=pct_rev_col):
for cell in row:
if cell.value is not None:
if cell.value >= 20:
cell.fill = high_fill
elif cell.value >= 10:
cell.fill = med_fill
else:
cell.fill = low_fill
wb.save(OUTPUT_PATH)
print(f"Report saved: {OUTPUT_PATH}")
Tip
The pattern of writing with pd.ExcelWriter first and then reopening with load_workbook is intentional. pd.ExcelWriter handles the data writing efficiently, while load_workbook gives you full access to openpyxl's formatting API on the already-written cells. Trying to do everything in a single with block using writer.book is possible but can lead to confusing interactions between pandas and openpyxl internals.
An ad-hoc script is fine once. A production-ready report runs every month without anyone touching it. Let's wrap the entire pipeline into a function that takes a transactions DataFrame and an analysis date, and returns both the scored DataFrame and the output path.
def build_rfm_report(
orders_df: pd.DataFrame,
analysis_date: datetime,
output_path: str = "rfm_report.xlsx",
customer_id_col: str = "customer_id",
order_id_col: str = "order_id",
order_date_col: str = "order_date",
order_value_col: str = "order_value"
) -> tuple[pd.DataFrame, str]:
"""
Full RFM segmentation pipeline.
Parameters
----------
orders_df : DataFrame with one row per order
analysis_date : Reference date for recency calculation
output_path : Where to write the Excel file
*_col params : Column name overrides for flexible input schemas
Returns
-------
(rfm_scored DataFrame, output_path string)
"""
# Validate required columns
required = {customer_id_col, order_id_col, order_date_col, order_value_col}
missing = required - set(orders_df.columns)
if missing:
raise ValueError(f"Missing required columns: {missing}")
# Standardize column names internally
df = orders_df.rename(columns={
customer_id_col: "customer_id",
order_id_col: "order_id",
order_date_col: "order_date",
order_value_col: "order_value"
}).copy()
df["order_date"] = pd.to_datetime(df["order_date"])
# Compute RFM metrics
rfm = df.groupby("customer_id").agg(
last_order_date=("order_date", "max"),
frequency=("order_id", "count"),
monetary=("order_value", "sum")
).reset_index()
rfm["recency"] = (analysis_date - rfm["last_order_date"]).dt.days
rfm = rfm.drop(columns=["last_order_date"])
rfm["monetary"] = rfm["monetary"].round(2)
# Score
rfm_scored = score_rfm(rfm)
rfm_scored["rfm_string"] = (
rfm_scored["r_score"].astype(str) +
rfm_scored["f_score"].astype(str) +
rfm_scored["m_score"].astype(str)
)
rfm_scored["rfm_score"] = rfm_scored[["r_score", "f_score", "m_score"]].sum(axis=1)
# Assign segments
conditions = [
(rfm_scored["r_score"] >= 4) & (rfm_scored["f_score"] >= 4) & (rfm_scored["m_score"] >= 4),
(rfm_scored["r_score"] >= 3) & (rfm_scored["f_score"] >= 3) & (rfm_scored["m_score"] >= 3),
(rfm_scored["r_score"] >= 4) & (rfm_scored["f_score"] <= 2),
(rfm_scored["r_score"] >= 4) & (rfm_scored["f_score"] >= 2) & (rfm_scored["m_score"] >= 2),
(rfm_scored["r_score"] == 3) & (rfm_scored["f_score"] >= 3),
(rfm_scored["r_score"] <= 2) & (rfm_scored["f_score"] >= 3) & (rfm_scored["m_score"] >= 3),
(rfm_scored["r_score"] <= 2) & (rfm_scored["f_score"] >= 4) & (rfm_scored["m_score"] >= 4),
(rfm_scored["r_score"] <= 2) & (rfm_scored["f_score"] <= 2) & (rfm_scored["m_score"] <= 2),
(rfm_scored["r_score"] <= 1) & (rfm_scored["f_score"] <= 1),
]
choices = [
"Champions", "Loyal Customers", "New Customers", "Promising",
"Need Attention", "At Risk", "Can't Lose Them", "Lost", "Hibernating"
]
rfm_scored["segment"] = np.select(conditions, choices, default="About to Sleep")
# Build all output tables and write Excel
# (call the export logic from earlier here, using rfm_scored)
# For brevity in this function signature, we return rfm_scored and
# call the export function separately
return rfm_scored, output_path
# Usage:
# rfm_result, path = build_rfm_report(orders_df, ANALYSIS_DATE, "jan_2024_rfm.xlsx")
For a deeper pattern on structuring reusable pipelines like this one, Structuring a Reusable Data Analysis Project: Functions, Modules, Notebooks, and Scripts covers how to split this across modules, add logging, and handle configuration cleanly.
Now that you've built the full pipeline, here are three exercises that will push your understanding beyond the tutorial code.
Exercise 1: Add a Trend Layer
The current report is a point-in-time snapshot. Extend the pipeline to run RFM scoring for two periods — the last 90 days and the previous 90 days — and add a segment_change column to the customer table indicating whether a customer moved up, down, or stayed in their segment. This requires running score_rfm() twice with filtered DataFrames and comparing the results. You'll need to handle the case where a customer appears in only one period.
Exercise 2: Decile Scoring
Marketing wants finer granularity. Modify score_rfm() to accept a q parameter (defaulting to 5 for quintiles) and test the report with deciles (q=10). How does the segment distribution change? Note that you'll also need to update the segment assignment rules, since the score range is now 1–10 per dimension rather than 1–5.
Exercise 3: Conditional Formatting Enhancement
The current Excel export applies a simple three-color revenue highlight. Extend it to add a "heat map" on the Customer Scores sheet: color the r_score, f_score, and m_score columns with a green-yellow-red gradient (5=dark green, 3=yellow, 1=red). Use openpyxl.styles.PatternFill with custom hex codes for each score value. This kind of formatting is exactly what makes an RFM export self-explanatory to a non-technical stakeholder.
Mistake 1: Forgetting to invert recency scoring
This is the single most common RFM bug. If you use labels=[1, 2, 3, 4, 5] for recency the same way you do for frequency and monetary, customers who bought yesterday get a score of 1 (worst) and customers who last bought two years ago get a 5 (best). The fix is explicit: labels=[5, 4, 3, 2, 1] for recency. Always test by confirming that your lowest recency values (most recent customers) have an r_score of 5.
# Verification check — run this after scoring
assert rfm_scored.loc[rfm_scored["recency"].idxmin(), "r_score"] == 5, \
"Recency inversion is broken — customer with lowest recency should have r_score=5"
Mistake 2: ValueError from pd.qcut() with duplicate bin edges
Frequency columns in particular are prone to this because many customers have identical counts. The duplicates="drop" argument prevents the error, but you must then verify that your resulting score distribution is reasonable.
# If you get ValueError, debug like this:
print(rfm["frequency"].value_counts().head(10))
# If a single value dominates (e.g., 60% of customers have frequency=1),
# you may want to handle that bucket separately before qcut.
Mistake 3: Using cut instead of qcut
pd.cut creates bins of equal width in value space. If 90% of your customers spent under $100 and a few whale accounts spent $10,000, cut will pack almost everyone into the first one or two bins. Use qcut for RFM — always. The article on Conditional Columns and Bucketing in pandas: Creating New Fields with np.where, cut, and map explains the difference between cut and qcut in detail.
Mistake 4: Running the analysis on returns/refunds included
If your order_value column includes negative values (refunds), your monetary metric is distorted. Filter to positive-value orders before computing RFM metrics: orders_df = orders_df[orders_df["order_value"] > 0]. Alternatively, net out returns at the customer level before aggregation.
Mistake 5: Wrong analysis date
If you set ANALYSIS_DATE to today's date in a report that runs on the 1st of each month, recency values shift slightly depending on when exactly the report runs. For reproducibility and comparability across months, always set a fixed, explicit snapshot date — typically the last day of the reporting period — not datetime.today().
Warning
If you're running this as an automated monthly report, do NOT use datetime.today() as your analysis date. Future runs will produce different recency values for the same transaction history, making month-over-month segment comparisons meaningless. Use a parameter like ANALYSIS_DATE = datetime(year, month, 1) based on the reporting period.
Mistake 6: Segment assignment order matters
In the np.select() approach, the first matching condition wins. If your conditions overlap, customers could be assigned to unexpected segments. For example, a 5-5-5 customer satisfies both "Champions" and "Loyal Customers" conditions. Always put the most restrictive conditions first. After running, do a sanity check: Champions should have the highest average RFM scores.
# Sanity check
print(rfm_scored.groupby("segment")["rfm_score"].mean().sort_values(ascending=False))
# Champions should be at the top
Mistake 7: Excel sheet names longer than 31 characters
openpyxl enforces Excel's 31-character sheet name limit. If you dynamically generate sheet names (e.g., using period names like "RFM Report January 2024"), truncate them: sheet_name[:31]. Exceeding this silently fails in some versions and raises an exception in others.
You've built a complete, production-grade RFM segmentation pipeline in pandas. Here's what the architecture accomplishes:
groupby().agg() callpd.qcut() with explicit quintile labels, with the critical recency inversion handled explicitlynp.select() with priority-ordered business rulesThe result isn't just a one-time deliverable — it's a parameterized function that can run monthly with minimal changes.
Where to go from here:
shift() and pct_change() to show how segment counts and revenue contribution are changing month over month — the approach is detailed in Comparing Periods and Calculating Month-over-Month, Year-over-Year, and Rolling Changes in pandas with shift and pct_changeRFM is one of those frameworks that gets more powerful the longer you run it. The first month is a snapshot. The sixth month is a trend. The first year tells you which segments your business is building toward — and which ones you're losing.
Python for Data Analysis