← All Python interview questions

RFM scoring for a customer base

HardPandas — CleaningNykaaDeloitte

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.