Sub topic 4
Building a cohort retention table
This chapter turns raw event data into a cohort retention table. You will assign each user to a cohort, compute each event's age, count distinct active users, and divide by cohort size. I assume you have read the earlier chapters on what a cohort is, what counts as an active event, and the difference between classic, bracket, and rolling retention. The code uses Python with pandas, and one SQL version is included.
What the table is
A cohort retention table has one row per cohort and one column per age. A cohort here is the group of users whose first event fell in the same calendar month. Age is the number of months since that first month. Each cell answers one question: of the users who started in this cohort, what fraction was active at this age?
The table uses classic retention, so a user counts at age N only if they were active in that exact period. A user who skips month 2 and returns in month 3 is missing from month 2 and present in month 3.
Always build the table in the same order:
- Reduce the events to the activity you decided counts as "active".
- Assign each user to a cohort, using their earliest period.
- Compute each event's age relative to its user's cohort.
- Count distinct users for each cohort and age.
- Divide by the age-0 count for that cohort.
Input data
The input is an event log with one row per event. It needs a user identifier and a timestamp. If your product has several event types, filter to the activity event first. Counting a login as activity when your product's value happens elsewhere will inflate retention.
The example below uses ten events from five users:
import numpy as np
import pandas as pd
events = pd.DataFrame({
"user_id": [1, 1, 1, 2, 2, 3, 3, 4, 5, 5],
"ts": pd.to_datetime([
"2026-01-05", "2026-02-10", "2026-03-03",
"2026-01-20", "2026-02-15",
"2026-02-02", "2026-03-12",
"2026-02-18",
"2026-03-05", "2026-03-20",
]),
})User 5 has two events in March. That is deliberate. The table counts distinct users, not events, so those two events must produce one active user.
Assign cohorts and ages
Convert each timestamp to a monthly period. Then find each user's earliest period and use it as their cohort. Age is the difference between the event's period and the cohort period, in months.
events["month"] = events["ts"].dt.to_period("M")
events["cohort"] = events.groupby("user_id")["month"].transform("min")
events["age"] = (
(events["month"].dt.year - events["cohort"].dt.year) * 12
+ (events["month"].dt.month - events["cohort"].dt.month)
)Do not compute age by subtracting two month numbers. January 2026 to January 2027 is 12 months, but the month numbers differ by 0. The year term handles that.
Using transform("min") keeps one row per event and copies each user's minimum into every one of their rows. Without it, you would have to merge the cohort back in.
Count and divide
Group by cohort and age and count distinct users. unstack moves age into the columns. fill_value=0 fills combinations where nobody was active.
active = (
events.groupby(["cohort", "age"])["user_id"]
.nunique()
.unstack(fill_value=0)
)
retention = active.div(active[0], axis=0)
print(retention.round(2))Printing active gives the raw counts:
age 0 1 2
cohort
2026-01 2 2 1
2026-02 2 1 0
2026-03 1 0 0Dividing each row by its age-0 value gives the retention table:
age 0 1 2
cohort
2026-01 1.0 1.0 0.5
2026-02 1.0 0.5 0.0
2026-03 1.0 0.0 0.0active.div(active[0], axis=0) divides each row by that row's own age-0 count. The axis=0 argument is what makes pandas align the divisor with rows. Without it, pandas would try to align active[0] with the columns and return mostly NaN.
Age 0 is 1.0 for every cohort by construction. Each user is active in their first month, because that is how the cohort was defined.
The SQL version
If your events live in a warehouse, the same logic works in SQL. This version is for PostgreSQL:
WITH monthly AS (
SELECT DISTINCT
user_id,
date_trunc('month', ts)::date AS month
FROM events
),
cohorts AS (
SELECT user_id, MIN(month) AS cohort
FROM monthly
GROUP BY user_id
)
SELECT
c.cohort,
(EXTRACT(YEAR FROM age(m.month, c.cohort)) * 12
+ EXTRACT(MONTH FROM age(m.month, c.cohort)))::int AS age,
COUNT(DISTINCT m.user_id) AS active_users
FROM monthly m
JOIN cohorts c USING (user_id)
GROUP BY c.cohort, age
ORDER BY c.cohort, age;The DISTINCT in the first CTE collapses multiple events in one month into one row per user and month. The result is long-format counts. Divide each count by the age-0 count for its cohort, either in SQL with a window function or in your BI tool.
Blank out periods that have not happened yet
The table above has a trap. The Mar cohort shows 0.0 at age 1, but age 1 for March is April, and the data ends in March. Nobody has had the chance to be active in April. A zero here means "not observed yet", not "everyone left".
Fix this by masking cells beyond each cohort's maximum observable age:
last = events["month"].max()
max_age = np.array([
(last.year - c.year) * 12 + (last.month - c.month)
for c in retention.index
])
observed = retention.columns.to_numpy()[None, :] <= max_age[:, None]
retention_observed = retention.where(observed)retention.where(observed) keeps cells where the mask is True and sets the rest to NaN. The result is the familiar triangle:
age 0 1 2
cohort
2026-01 1.0 1.0 0.5
2026-02 1.0 0.5 NaN
2026-03 1.0 NaN NaNThe newest cohort's current period is also incomplete if you run the table mid-month. Either drop the latest partial period, or label it clearly. Otherwise the last observed column understates retention for every cohort.
Check cohort sizes
Retention percentages hide how many users stand behind them. Keep the age-0 count next to the table:
sizes = active[0].rename("cohort_size")
table = retention_observed.round(2).join(sizes)
print(table)In this toy example the cohorts have 1 to 2 users, so one user moving changes a cell by 50 or 100 percentage points. Real tables have the same problem at smaller scale. A cohort of 30 users has a standard error of roughly 9 percentage points on a retention rate near 50 percent. Treat differences smaller than that as noise.
Choices that change the table
Each of these changes the numbers, so write them down with the table:
| Choice | Options | Effect |
|---|---|---|
| Period length | Day, week, month | Shorter periods make a noisier but faster-reacting table. Match the natural usage frequency of the product. |
| Cohort anchor | First event, signup, first purchase | Anchoring on signup includes users who never activated, so age-0 retention is below 100%. |
| Activity event | Any event, core action | A looser event gives higher retention and a weaker signal. |
| Retention type | Classic, bracket, rolling | Rolling is always at least as high as classic for the same data. |
| Time zone | UTC, user local | Users near a period boundary can move to a different cohort. |
Common errors
- Counting events instead of users. Use
nunique()on the user ID. A heavy user with 50 events in one month must count once. - Dividing by the wrong denominator. Each row divides by its own cohort size, not by the total across all cohorts.
- Age computed from calendar month numbers. Include the year difference, as shown above.
- Mixed time zones. Convert all timestamps to one zone before taking the month.
- Test and internal users in the log. Exclude them before assigning cohorts. They tend to be heavy and loyal users, and they inflate early cohorts.
- Reading zeros as churn. Mask unobserved cells before any chart or average.
What the table gives you
The table is an input to the next steps in the tutorial. Reading across a row shows one cohort's decay. Reading down a column compares cohorts at the same age. You should be able to regenerate it from raw events at any time, so keep the code and the definitions in one place, not in a spreadsheet that someone edits by hand.
Exercise
A cohort table is built from events up to 2026-03-31. The cohort for 2026-02 shows 0.00 at age 2. A teammate says "all February users churned by month 2". What is wrong with that reading, and how do you fix the table?
Show answer
Age 2 for the February cohort is April 2026, which is after the data ends, so nobody could have been active yet. The 0.00 means "not observed", not "zero retention". Compute each cohort's maximum observable age from the last period in the data, and set cells with a larger age to NaN, for example with retention.where(observed).
Exercise
Why does the code use active.div(active[0], axis=0) and not active / active[0]?
Show answer
active / active[0] divides a DataFrame by a Series, and pandas aligns the Series index with the DataFrame's columns. The Series index is the cohort labels, so the alignment fails and the result is mostly NaN. div(..., axis=0) aligns the Series with the rows, so each row is divided by its own age-0 count.