1
---
2
name: Cohort Analysis
3
description: Track and analyze user cohorts over time, calculate retention rates, and identify behavioral patterns for customer lifecycle and retention analysis
4
---
5
6
# Cohort Analysis
7
8
## Overview
9
10
Cohort analysis tracks groups of users with shared characteristics over time, revealing patterns in retention, engagement, and lifetime value.
11
12
## When to Use
13
14
- Measuring user retention rates and identifying when users churn
15
- Analyzing customer lifetime value (LTV) and payback periods
16
- Comparing performance across different user acquisition channels or campaigns
17
- Understanding how product changes affect different user groups over time
18
- Tracking engagement patterns and identifying early warning signs of churn
19
- Evaluating the long-term impact of onboarding improvements or feature releases
20
21
## Core Concepts
22
23
- **Cohort**: Group of users sharing a characteristic (signup date, region, etc.)
24
- **Cohort Size**: Initial group size
25
- **Retention Rate**: Percentage remaining active
26
- **Churn Rate**: Percentage who left
27
- **Retention Curve**: How cohort degrades over time
28
29
## Cohort Types
30
31
- **Acquisition Date**: Users grouped by signup period
32
- **Behavioral**: Users grouped by actions taken
33
- **Revenue**: Users grouped by purchase value
34
- **Geographic**: Users grouped by location
35
- **Demographic**: Users grouped by characteristics
36
37
## Implementation with Python
38
39
```python
40
import pandas as pd
41
import numpy as np
42
import matplotlib.pyplot as plt
43
import seaborn as sns
44
45
# Create sample user lifecycle data
46
np.random.seed(42)
47
48
# Generate user data
49
n_users = 5000
50
users = []
51
52
for user_id in range(n_users):
53
signup_month = np.random.choice(range(1, 13))
54
lifetime_months = np.random.poisson(6) + 1
55
56
for month in range(1, lifetime_months + 1):
57
users.append({
58
'user_id': user_id,
59
'signup_month': signup_month,
60
'month': month,
61
'active': 1,
62
})
63
64
df = pd.DataFrame(users)
65
66
# Add derived columns
67
df['cohort_month'] = df['signup_month']
68
df['cohort_age'] = df['month'] # Could be day, week, etc.
69
df['date'] = pd.to_datetime('2023-01-01') + pd.to_timedelta(df['signup_month'] * 30, unit='D')
70
71
print("User Data Summary:")
72
print(df.head(10))
73
74
# 1. Cohort Table (Retention Matrix)
75
cohort_data = df.groupby(['cohort_month', 'cohort_age']).agg({
76
'user_id': 'nunique'
77
}).reset_index()
78
cohort_data.columns = ['cohort_month', 'cohort_age', 'unique_users']
79
80
# Create pivot table
81
cohort_pivot = cohort_data.pivot(index='cohort_month', columns='cohort_age', values='unique_users')
82
83
print("\nCohort Sizes (Raw User Counts):")
84
print(cohort_pivot)
85
86
# 2. Cohort Retention (as percentage of cohort size)
87
cohort_size = cohort_pivot.iloc[:, 0]
88
retention_table = cohort_pivot.divide(cohort_size, axis=0) * 100
89
90
print("\nCohort Retention Rate (%):")
91
print(retention_table.round(1))
92
93
# 3. Visualize Retention Matrix
94
fig, axes = plt.subplots(2, 1, figsize=(14, 8))
95
96
# Heatmap of raw counts
97
sns.heatmap(cohort_pivot, annot=True, fmt='g', cmap='YlOrRd', ax=axes[0],
98
cbar_kws={'label': 'User Count'})
99
axes[0].set_title('Cohort Sizes - User Counts')
100
axes[0].set_xlabel('Cohort Age (Months)')
101
axes[0].set_ylabel('Cohort Month')
102
103
# Heatmap of retention rates
104
sns.heatmap(retention_table, annot=True, fmt='.0f', cmap='RdYlGn', vmin=0, vmax=100,
105
ax=axes[1], cbar_kws={'label': 'Retention %'})
106
axes[1].set_title('Cohort Retention Rates (%)')
107
axes[1].set_xlabel('Cohort Age (Months)')
108
axes[1].set_ylabel('Cohort Month')
109
110
plt.tight_layout()
111
plt.show()
112
113
# 4. Retention Curve
114
fig, ax = plt.subplots(figsize=(12, 6))
115
116
# Plot retention curves for each cohort
117
for cohort_month in cohort_pivot.index[:8]: # First 8 cohorts
118
cohort_retention = retention_table.loc[cohort_month]
119
ax.plot(cohort_retention.index, cohort_retention.values, marker='o', label=f'Cohort {cohort_month}')
120
121
ax.set_xlabel('Cohort Age (Months)')
122
ax.set_ylabel('Retention Rate (%)')
123
ax.set_title('Retention Curves by Cohort')
124
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
125
ax.grid(True, alpha=0.3)
126
ax.set_ylim([0, 105])
127
128
plt.tight_layout()
129
plt.show()
130
131
# 5. Average Retention Curve
132
fig, ax = plt.subplots(figsize=(10, 6))
133
134
# Calculate average retention at each age
135
avg_retention = retention_table.mean()
136
ax.plot(avg_retention.index, avg_retention.values, marker='o', linewidth=2, markersize=8, color='navy')
137
ax.fill_between(avg_retention.index, avg_retention.values, alpha=0.3, color='navy')
138
139
# Add confidence interval
140
std_retention = retention_table.std()
141
ax.fill_between(std_retention.index,
142
avg_retention - std_retention,
143
avg_retention + std_retention,
144
alpha=0.2, color='navy', label='±1 Std Dev')
145
146
ax.set_xlabel('Cohort Age (Months)')
147
ax.set_ylabel('Retention Rate (%)')
148
ax.set_title('Average Retention Curve with Confidence Band')
149
ax.legend()
150
ax.grid(True, alpha=0.3)
151
ax.set_ylim([0, 105])
152
153
plt.tight_layout()
154
plt.show()
155
156
# 6. Churn Rate
157
churn_rate = 100 - retention_table
158
print("\nChurn Rates (%):")
159
print(churn_rate.round(1).head())
160
161
# 7. Revenue Cohort Analysis
162
# Add revenue data
163
np.random.seed(42)
164
df['revenue'] = np.random.exponential(50, len(df))
165
166
# Revenue by cohort
167
revenue_data = df.groupby(['cohort_month', 'cohort_age']).agg({
168
'revenue': 'sum',
169
'user_id': 'nunique'
170
}).reset_index()
171
revenue_data['revenue_per_user'] = revenue_data['revenue'] / revenue_data['user_id']
172
173
revenue_pivot = revenue_data.pivot(index='cohort_month', columns='cohort_age', values='revenue')
174
rpu_pivot = revenue_data.pivot(index='cohort_month', columns='cohort_age', values='revenue_per_user')
175
176
# Visualize revenue
177
fig, axes = plt.subplots(2, 1, figsize=(14, 8))
178
179
sns.heatmap(revenue_pivot, annot=True, fmt='.0f', cmap='YlGnBu', ax=axes[0],
180
cbar_kws={'label': 'Total Revenue ($)'})
181
axes[0].set_title('Total Revenue by Cohort')
182
axes[0].set_xlabel('Cohort Age (Months)')
183
axes[0].set_ylabel('Cohort Month')
184
185
sns.heatmap(rpu_pivot, annot=True, fmt='.2f', cmap='YlGnBu', ax=axes[1],
186
cbar_kws={'label': 'Revenue per User ($)'})
187
axes[1].set_title('Revenue per User by Cohort')
188
axes[1].set_xlabel('Cohort Age (Months)')
189
axes[1].set_ylabel('Cohort Month')
190
191
plt.tight_layout()
192
plt.show()
193
194
# 8. Lifetime Value Calculation
195
df['month_since_signup'] = df['cohort_age']
196
ltv_data = df.groupby('user_id').agg({
197
'revenue': 'sum',
198
'cohort_month': 'first',
199
'month_since_signup': 'max',
200
}).reset_index()
201
ltv_data.columns = ['user_id', 'lifetime_value', 'cohort_month', 'lifetime_months']
202
203
# Average LTV by cohort
204
ltv_by_cohort = ltv_data.groupby('cohort_month')['lifetime_value'].agg(['mean', 'median', 'std'])
205
206
print("\nLifetime Value by Cohort:")
207
print(ltv_by_cohort.round(2))
208
209
fig, ax = plt.subplots(figsize=(10, 6))
210
ltv_by_cohort['mean'].plot(kind='bar', ax=ax, color='skyblue', edgecolor='black')
211
ax.set_title('Average Lifetime Value by Cohort')
212
ax.set_xlabel('Cohort Month')
213
ax.set_ylabel('Lifetime Value ($)')
214
ax.grid(True, alpha=0.3, axis='y')
215
plt.tight_layout()
216
plt.show()
217
218
# 9. Cohort Composition Over Time
219
fig, ax = plt.subplots(figsize=(12, 6))
220
221
# Active users per month by cohort
222
active_by_month = df.groupby(['date', 'cohort_month']).size().reset_index(name='active_users')
223
pivot_active = active_by_month.pivot(index='date', columns='cohort_month', values='active_users')
224
225
pivot_active.plot(ax=ax, marker='o')
226
ax.set_title('Active Users Per Month by Cohort')
227
ax.set_xlabel('Month')
228
ax.set_ylabel('Active Users')
229
ax.legend(title='Cohort Month', bbox_to_anchor=(1.05, 1))
230
ax.grid(True, alpha=0.3)
231
232
plt.tight_layout()
233
plt.show()
234
235
# 10. Cohort Summary Metrics
236
summary_metrics = pd.DataFrame({
237
'Cohort Month': cohort_size.index,
238
'Initial Size': cohort_size.values,
239
'Month 1 Retention': retention_table.iloc[:, 0].values,
240
'Month 3 Retention': retention_table.iloc[:, min(2, retention_table.shape[1]-1)].values,
241
'Avg LTV': ltv_by_cohort['mean'].values,
242
})
243
244
print("\nCohort Summary Metrics:")
245
print(summary_metrics.round(2))
246
247
# 11. Visualization comparison
248
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
249
250
# Month 1 vs Month 3 retention
251
ax_plot = axes[0]
252
months = ['Month 1', 'Month 3']
253
month_1_ret = retention_table.iloc[:, 0].mean()
254
month_3_ret = retention_table.iloc[:, min(2, retention_table.shape[1]-1)].mean()
255
ax_plot.bar(months, [month_1_ret, month_3_ret], color=['#1f77b4', '#ff7f0e'], edgecolor='black')
256
ax_plot.set_ylabel('Retention Rate (%)')
257
ax_plot.set_title('Average Retention by Milestone')
258
ax_plot.set_ylim([0, 100])
259
for i, v in enumerate([month_1_ret, month_3_ret]):
260
ax_plot.text(i, v + 2, f'{v:.1f}%', ha='center')
261
262
# Cohort size trend
263
axes[1].plot(cohort_size.index, cohort_size.values, marker='o', linewidth=2, markersize=8)
264
axes[1].set_xlabel('Cohort Month')
265
axes[1].set_ylabel('Cohort Size')
266
axes[1].set_title('Cohort Sizes Over Time')
267
axes[1].grid(True, alpha=0.3)
268
269
# LTV trend
270
axes[2].plot(ltv_by_cohort.index, ltv_by_cohort['mean'].values, marker='o', linewidth=2, markersize=8, color='green')
271
axes[2].set_xlabel('Cohort Month')
272
axes[2].set_ylabel('Average Lifetime Value ($)')
273
axes[2].set_title('LTV Trend by Cohort')
274
axes[2].grid(True, alpha=0.3)
275
276
plt.tight_layout()
277
plt.show()
278
279
print("\nCohort analysis complete!")
280
```
281
282
## Key Metrics
283
284
- **Retention Rate**: % of cohort active
285
- **Churn Rate**: % of cohort lost
286
- **Day/Month 1 Retention**: Early engagement
287
- **Lifetime Value**: Total revenue per user
288
- **Payback Period**: Time to recover CAC
289
290
## Insights to Look For
291
292
- Early retention predictors
293
- Differences between cohorts
294
- Seasonal patterns
295
- Engagement degradation
296
- Revenue trends
297
298
## Deliverables
299
300
- Cohort retention matrix
301
- Retention curve visualization
302
- Churn rate analysis
303
- Lifetime value calculations
304
- Revenue per cohort
305
- Executive summary with insights
306
- Actionable recommendations
307