Skip to content

ftalamo/pyFastRTM

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pyFastRTM

RFM customer segmentation Python + pandas. No database required.


What is RFM?

RFM is a customer segmentation method based on three behavioral metrics:

Metric Definition Score 4 means
Recency Days since last order Bought very recently
Frequency Number of orders Buys very often
Monetary Total spend Spends the most

Each customer gets a score from 1 to 4 on each metric (4 = best), producing a three-digit code like 444 (Champion) or 111 (Lost).


Quick start

# 1. Install dependencies
pip install -r requirements.txt

# 2. Generate sample data (or drop your own CSV in data/)
python generate_sample_data.py

# 3. Run the analysis
python rfm.py

Output: data/rfm_output.csv + data/rfm_plot.png


Input format

The script expects a CSV at data/sample_orders.csv with these columns:

Column Type Example
customer_id string C00042
order_date date 2024-03-15
grand_total float 149.90

Segments

Segment R F M Description
Champions 4 4 3–4 Best customers. Reward them.
Loyal 3–4 3–4 3–4 Frequent buyers. Upsell.
Potential Loyalist 3–4 2 2 Recent, not yet committed. Nurture.
Recent Customers 3–4 1 1 Just bought once. Onboard well.
Needs Attention 2 2–3 2–3 Above average but fading. Re-engage.
Can't Lose Them 1 3–4 3–4 Used to buy a lot. Win back.
At Risk 1 2–3 2–3 Haven't bought in a while. Act now.
Hibernating 1 1–2 1 Low engagement, long ago.
Lost 1 1 1 Gone. Last resort campaigns only.

How scoring works

Each metric is divided into four quartiles using pd.qcut:

rfm["R"] = pd.qcut(rfm["recency"],                    q=4, labels=[4,3,2,1]).astype(int)
rfm["F"] = pd.qcut(rfm["frequency"].rank(method="first"), q=4, labels=[1,2,3,4]).astype(int)
rfm["M"] = pd.qcut(rfm["monetary"],                   q=4, labels=[1,2,3,4]).astype(int)

This replaces the original T-SQL WHILE loop that ran 4 UPDATE TOP(N) PERCENT passes — same logic, single vectorized operation.


File structure

├── rfm.py                   # Main script
├── generate_sample_data.py  # Synthetic data generator
├── requirements.txt
├── RFM.sql                  # Original T-SQL script (preserved)
├── notebooks/
│   └── rfm_notebook.ipynb   # Step-by-step walkthrough
└── data/
    ├── sample_orders.csv    # Generated by generate_sample_data.py
    ├── rfm_output.csv       # Generated by rfm.py
    └── rfm_plot.png         # Generated by rfm.py

License

MIT

About

quick RFM analysis written in python + pandas

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors