Marketing wants a classic RFM segmentation. Given a transactions frame with customer_id, order_date and amount, and a fixed as_of date:
- Recency: days between the customer's most recent order and
as_of - Frequency: number of orders
- Monetary: total amount spent
Write a function rfm(df, as_of) that returns a DataFrame indexed by customer_id with columns recency, frequency and monetary, sorted by monetary descending.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
df = pd.DataFrame(
{
"customer_id": [101, 101, 102, 103, 103, 103, 104],
"order_date": [
"2026-03-01", "2026-03-20", "2026-01-15",
"2026-03-28", "2026-02-10", "2026-03-05", "2026-02-25",
],
"amount": [1500, 2500, 900, 4000, 1200, 800, 3100],
}
)
as_of = "2026-04-01"- Step 1: Work on `df.copy()` so parsing the dates does not mutate the caller's frame — a habit interviewers notice.
- Step 2: `pd.to_datetime` on the column and `pd.Timestamp(as_of)` for the cutoff put both sides on the same type so they can be subtracted.
- Step 3: Named aggregation (`last_order=("order_date", "max")`) computes all three metrics in a single `groupby` pass and names the output columns directly.
- Step 4: Subtracting timestamps yields a Timedelta Series; `.dt.days` converts it to the integer day count recency needs.
- Step 5: Reorder to `recency, frequency, monetary` and sort by spend descending so the most valuable customers sit at the top.
import pandas as pd
def rfm(df, as_of):
data = df.copy()
data["order_date"] = pd.to_datetime(data["order_date"])
cutoff = pd.Timestamp(as_of)
agg = data.groupby("customer_id").agg(
last_order=("order_date", "max"),
frequency=("order_date", "count"),
monetary=("amount", "sum"),
)
agg["recency"] = (cutoff - agg["last_order"]).dt.days
return agg[["recency", "frequency", "monetary"]].sort_values("monetary", ascending=False)Learn the concept first
Stuck on Pandas — Cleaning? These free Python lessons teach it step by step.
More Pandas — Cleaning questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program