What You Will Learn
- How to analyze customer behavior from raw event logs
- How to combine RFM segmentation, cohort analysis, and churn measurement in one project
- How to translate behavior insights into retention recommendations
- The full Python code for every step
Why This Topic Matters
This is the second capstone. While lesson 39 focused on sales (transactions), this one focuses on customers (behavior over time). Together they cover the two most common analytics projects in industry. If you can do both, you can handle ~80% of real analyst work.
The Business Question
You work for a subscription app. The Head of Growth asks:
"Are we keeping the customers we acquire? Where are we losing them?"
Step 1 — Restate the Question
You translate to a measurable data question:
"For customers who signed up in each month from Jan to Aug 2026, what is the retention curve over the first 6 months? Which RFM segments show the highest churn? What behaviors predict 30-day retention?"
Step 2 — The Data
Synthetic event dataset. ~5,000 customers, ~50,000 events, January through August 2026. Three columns:
| user_id | event_date | event_type |
|---|---|---|
| U001 | 2026-01-15 | signup |
| U001 | 2026-01-16 | login |
| U001 | 2026-01-18 | purchase |
| U002 | 2026-01-22 | signup |
| ... | ... | ... |
Event types: signup, login, purchase, support_ticket, downgrade, churn.
Step 3 — Loading and Cleaning
import pandas as pd
df = pd.read_csv("customer_events_2026.csv")
df["event_date"] = pd.to_datetime(df["event_date"])
# Sanity checks
print(df.shape) # (~50,000, 3)
print(df["event_type"].value_counts())
print(df["user_id"].nunique()) # ~5,000 unique users
print(df.duplicated().sum()) # 0 ideally
# Check for users with multiple signups (should be 1 each)
signups = df[df["event_type"] == "signup"]
multi_signup = signups["user_id"].value_counts()
print(multi_signup[multi_signup > 1]) # investigate any duplicates
# Drop duplicate (user, event_type, event_date) rows
df = df.drop_duplicates(subset=["user_id", "event_type", "event_date"])
Step 4 — Build the Customer-Level Table
Aggregate events into one row per customer, with derived metrics.
# Signup date per user
signups = df[df["event_type"] == "signup"][["user_id", "event_date"]] .rename(columns={"event_date": "signup_date"})
# Last activity date per user
last_activity = df.groupby("user_id")["event_date"].max() .rename("last_activity_date")
# Purchase count and total spend per user
purchases = df[df["event_type"] == "purchase"]
purchase_summary = purchases.groupby("user_id").agg(
purchase_count=("event_type", "count"),
).join(
# If there's an amount column, sum it; here we use count only
purchases.groupby("user_id").size().rename("purchase_count_2")
)
# Combine
customers = signups.set_index("user_id") .join(last_activity) .join(purchase_summary)
# Compute recency (days since last activity, relative to analysis date)
analysis_date = df["event_date"].max() + pd.Timedelta(days=1)
customers["recency_days"] = (analysis_date - customers["last_activity_date"]).dt.days
# Compute tenure (days since signup)
customers["tenure_days"] = (analysis_date - customers["signup_date"]).dt.days
# Flag churned: no activity in last 30 days
customers["is_churned"] = customers["recency_days"] > 30
print(customers.head())
Step 5 — RFM Segmentation
# Recency score (lower recency = higher score)
customers["R"] = pd.qcut(customers["recency_days"], 5,
labels=[5,4,3,2,1], duplicates="drop")
# Frequency score (higher = better)
customers["F"] = pd.qcut(customers["purchase_count"].rank(method="first"),
5, labels=[1,2,3,4,5])
# Monetary (use purchase_count as proxy if no amount column)
customers["M"] = customers["F"] # simplified
customers["rfm"] = customers["R"].astype(str) + customers["F"].astype(str) + customers["M"].astype(str)
# Map RFM patterns to segment labels
def segment(row):
r, f, m = int(row["R"]), int(row["F"]), int(row["M"])
if r >= 4 and f >= 4: return "Champions"
if r >= 4 and f <= 2: return "Recent"
if r <= 2 and f >= 4: return "At Risk"
if r <= 2 and f <= 2: return "Churned"
return "Middle"
customers["segment"] = customers.apply(segment, axis=1)
print(customers["segment"].value_counts())
Example output
Middle 1850
Champions 1240
Recent 720
Churned 580
At Risk 610
Step 6 — Cohort Retention Analysis
# Signup month per user
customers["signup_month"] = customers["signup_date"].dt.to_period("M")
# For each user, find which months they were active
df["month"] = df["event_date"].dt.to_period("M")
active_months = df[["user_id", "month"]].drop_duplicates()
# Join signup month
active_months = active_months.merge(
customers[["signup_month"]].reset_index(),
on="user_id"
)
# Compute month_index (0 = signup month)
active_months["month_index"] = (
active_months["month"] - active_months["signup_month"]
).apply(lambda x: x.n)
# Cohort table: signup_month × month_index → distinct active users
cohort = active_months.groupby(["signup_month", "month_index"]) ["user_id"].nunique().unstack(level=1)
# Convert to % of month 0 (signup month = 100%)
cohort_pct = cohort.div(cohort[0], axis=0) * 100
print(cohort_pct.round(0))
Example cohort table
| Signup month | M0 | M1 | M2 | M3 | M4 | M5 |
|---|---|---|---|---|---|---|
| 2026-01 | 100 | 62 | 48 | 41 | 36 | 32 |
| 2026-02 | 100 | 58 | 45 | 38 | 33 | — |
| 2026-03 | 100 | 65 | 52 | 43 | — | — |
| 2026-04 | 100 | 71 | 58 | — | — | — |
| 2026-05 | 100 | 74 | — | — | — | — |
Reading down the M1 column: 62 → 58 → 65 → 71 → 74. Newer cohorts retain better. This is the most important finding in the project.
Step 7 — Churn Drivers
Compare churned vs active customers on key behaviors:
churned = customers[customers["is_churned"]]
active = customers[~customers["is_churned"]]
print("Avg purchase count:")
print(f" Active: {active['purchase_count'].mean():.2f}")
print(f" Churned: {churned['purchase_count'].mean():.2f}")
print("Avg tenure:")
print(f" Active: {active['tenure_days'].mean():.0f} days")
print(f" Churned: {churned['tenure_days'].mean():.0f} days")
# Did they file support tickets?
tickets = df[df["event_type"] == "support_ticket"] .groupby("user_id").size().rename("ticket_count")
customers = customers.join(tickets)
print("Support ticket rate:")
print(f" Active: {customers.loc[~customers['is_churned'], 'ticket_count'].fillna(0).gt(0).mean():.1%}")
print(f" Churned: {customers.loc[customers['is_churned'], 'ticket_count'].fillna(0).gt(0).mean():.1%}")
Typical findings
- Customers who never made a purchase in their first 7 days churn at 2× the rate of those who did.
- Customers who filed a support ticket churn at 1.5× the rate of those who did not.
- Customers in the "At Risk" RFM segment (low recency, high frequency) are 3× more likely to churn next month than "Champions".
Step 8 — Visualization
import matplotlib.pyplot as plt
import seaborn as sns
fig, axes = plt.subplots(2, 2, figsize=(13, 9))
# Segment sizes
customers["segment"].value_counts().plot(
kind="bar", ax=axes[0,0], color="steelblue")
axes[0,0].set_title("Customer Count by RFM Segment")
axes[0,0].set_ylabel("Customers")
# Cohort retention heatmap
sns.heatmap(cohort_pct, annot=True, fmt=".0f",
cmap="YlGnBu", ax=axes[0,1])
axes[0,1].set_title("Cohort Retention (%)")
axes[0,1].set_xlabel("Months since signup")
axes[0,1].set_ylabel("Signup month")
# Churn rate by segment
customers.groupby("segment")["is_churned"].mean().sort_values() .plot(kind="barh", ax=axes[1,0], color="crimson")
axes[1,0].set_title("Churn Rate by Segment")
axes[1,0].set_xlabel("Churn Rate")
# Purchase count: active vs churned
customers.boxplot(column="purchase_count", by="is_churned", ax=axes[1,1])
axes[1,1].set_title("Purchase Count: Active vs Churned")
axes[1,1].set_xlabel("Is Churned")
plt.tight_layout()
plt.savefig("customer_behavior_dashboard.png", dpi=120, bbox_inches="tight")
plt.show()
Step 9 — Insights
- Newer cohorts retain better. Jan cohort: 62% at M1. May cohort: 74% at M1. The product changes since January are working — newer users are sticking around longer.
- "At Risk" segment is the highest churn risk. 580 customers in the At Risk and Churned segments combined. They represent significant historical revenue but are disengaging now.
- First-week purchase is the strongest predictor of retention. Customers who purchased in their first 7 days retain at ~60% at M3; those who did not retain at ~28%.
- Support tickets correlate with churn. Customers who filed a ticket churned at 1.5× the rate of those who did not. Either the issues were unresolved, or the friction of filing a ticket disengaged them.
Step 10 — Recommendations
Recommendation 1 — Run a win-back campaign for "At Risk" customers
| Element | Detail |
|---|---|
| Finding | 610 customers in the "At Risk" segment — used to be active, now disengaging. |
| Recommendation | Targeted email + push campaign with 20% discount on their most-purchased category. Personalize the subject line with their last purchase. |
| Expected outcome | 15% reactivation rate → ~92 customers reactivated. Average retained customer value ~₹2,400 → ~₹2.2L recovered revenue. |
| Cost | ₹40,000 (campaign tool + discount cost). |
| Success measure | At Risk segment shrinks by ≥10% within 30 days. |
Recommendation 2 — Optimize the first-week onboarding
| Element | Detail |
|---|---|
| Finding | Customers who purchased in the first 7 days retain at 2× the rate of those who did not. |
| Recommendation | Add a first-purchase prompt in the app onboarding flow: a "Complete your first purchase" checklist with a 10% discount on the first order. |
| Expected outcome | First-week purchase rate from 45% to 60%. M3 retention from 41% to 48%. |
| Cost | ₹30,000 (in-app prompt development + 10% discount cost spread across new users). |
| Success measure | First-week purchase rate ≥ 60% for the next cohort. |
Recommendation 3 — Investigate support ticket → churn correlation
Before recommending a fix, run the investigation workflow from lesson 38:
- Are support tickets resolved quickly enough?
- Do customers churn because of the issue, or because of poor support handling?
- Compare churn rates for resolved vs unresolved tickets.
This finding needs root-cause analysis before a recommendation.
The Final Presentation
10-minute structure:
- 1 min: the question and what data you used.
- 2 min: cohort retention chart — newer cohorts retain better.
- 2 min: RFM segment sizes + churn rate by segment.
- 2 min: first-week purchase as a retention driver.
- 3 min: two recommendations + one investigation item.
Common Mistakes
- Treating "churn" as a single event. Churn is a process. Track the warning signs (declining login frequency, shorter sessions) before the churn event itself.
- Comparing cohorts without controlling for age. A Jan cohort at M3 and an Apr cohort at M3 are comparable. A Jan cohort at M6 vs an Apr cohort at M3 is not.
- Confusing correlation with causation in churn drivers. Filing a support ticket correlates with churn, but did it cause it? Test before claiming.
- Recommending a win-back without segmenting it. "Send a discount to all churned users" wastes money. Target only the segment likely to respond.
- Forgetting to measure whether the recommendation worked. Always define the success metric and revisit it 30–60 days later.
Practical Exercise (60–90 minutes)
- Generate a synthetic event dataset: 1,000 users, 10,000 events, 6 months. Vary the event types and dates realistically.
- Run the full pipeline: clean → customer table → RFM → cohorts → churn drivers.
- Build the 4-chart dashboard.
- Write a 1-page brief with 3 insights and 2 recommendations.
- Compare your recommendations to those above. Did you find different insights? Why?
Mini Challenge
Extend the project: add a "monthly active user" (MAU) trend chart. Compute MAU for each of the 8 months. Is MAU growing, flat, or declining? How does this compare to the cohort retention finding? If MAU is growing while retention is improving, the business is healthy. If MAU is growing while retention is declining, growth is masking a retention problem — a critical insight.
Key Takeaways
- Customer analytics = segmentation + cohort + churn-driver analysis, combined.
- RFM gives you the snapshot; cohorts give you the trend; churn drivers tell you the cause.
- Newer cohorts retaining better is the single most positive signal a product can show.
- First-week behavior is often the strongest predictor of long-term retention.
- Recommendations need: action, expected outcome, cost, success measure — same as any analytics project.
Previously learned: The entire course (lessons 01–39).
Today: You completed the second capstone project, applying segmentation, cohort, and churn analysis to a realistic customer event dataset.
Congratulations: You have finished the Data + Analytics course. You can now frame business questions, clean and analyze data with Excel/SQL/Python, apply practical statistics, design honest visualizations, and run end-to-end analytics projects — exactly what a working data analyst does.
FAQ
What should I learn next?
Three natural next steps: (1) A/B testing and causal inference — how to actually prove a recommendation works. (2) Power BI or Tableau — for building shared dashboards at scale. (3) Machine learning basics — for predictive analytics (the next level above the descriptive/diagnostic work in this course).
How do I show this skill to employers?
Put both capstone projects on GitHub with clean README files. Write a 1-page summary of each. Mention the metrics you moved (or hypothetically moved) and the recommendations you made. Employers care more about the recommendation quality than the code quality at the entry level.
Is this course enough to get a job as an analyst?
It is enough to start interviewing for junior analyst roles. The technical skills (SQL, pandas, basic stats) plus the two capstone projects will get you past most resume screens. The remaining piece is domain knowledge — pick an industry (e-commerce, fintech, SaaS, healthcare) and learn its specific metrics and patterns.
Comments
Comments
Post a Comment