Most retention cohort matrices shared in product reviews are wrong, and the code is rarely the reason. The pandas part takes about 20 lines and few people get it badly wrong.
What goes wrong is the set of decisions made before the first line: which event puts a user into a cohort, which event counts as "retained", whether "month 1" means the next calendar month or days 30 to 59, and what to show in cells for periods that have not finished yet. Each choice can move the headline number by 10 points or more, and none of them shows up in the chart.
This guide is laid out like a decision memo. It sets out the question the matrix has to answer, the options for defining retention, a recommendation, and then the full pandas procedure with the checks that catch the usual errors. The code was written and run against pandas 3.0, and it uses only standard operations that also work on 2.x.
The question the matrix has to answer
A cohort matrix answers one question: of the users who started in a given period, what share were still active in each later period? Rows are cohorts, columns are periods since start, cells are percentages. Read across a row and you see one cohort decaying. Read down a column and you see whether newer cohorts retain better than older ones at the same age, which is usually what a product team actually wants to know after a release, an onboarding change or a new acquisition channel.
Before writing code, write down four definitions. They are worth stating as a box at the top of any notebook that produces the matrix.
Cohort event: the action that puts a user into a cohort. Signup, first purchase, first app open and first completed onboarding all give different matrices. A subscription business usually wants first payment; a free product, first meaningful action.
Cohort period: the bucket of start dates grouped into one row, commonly a calendar month or a week. Weekly cohorts give faster feedback with noisier rows.
Retention event: the action that counts as "still here" in a later period. Any login is the loosest choice. A core action (an order, a played session, a report viewed) is stricter and usually more honest.
Period index: the age of the cohort at the time of the activity, 0 for the start period, 1 for the next, and so on. Whether it is counted in calendar months or in fixed day windows changes the meaning of every column.
A matrix built without these four written down will be reinterpreted by every reader. Someone will compare it with a dashboard that uses signups instead of first purchases, see a 15 point difference and conclude that one of them is broken.
Three ways to define a retained user
The options below all appear in real analytics tools, and they answer slightly different questions. The table compares them on the points that matter for a pandas build.
| Definition | What a cell means | Strength | Weakness | pandas effort |
|---|---|---|---|---|
| Calendar month retention | Share of cohort active at least once in calendar month k after the start month | Simple, matches finance reporting | A user who signs up on the 31st reaches "month 1" one day later | Low: to_period("M") |
| N-day retention (fixed windows) | Share active in a window such as days 28 to 34 after their own start | Every user gets the same exposure time | More code; windows need to be chosen and explained | Medium: day differences |
| Unbounded (rolling) retention | Share active on day N or any later day | Smooth curve, good for long cycles | Rises when a cohort reactivates; never final until much later | Medium, plus a cutoff rule |
My recommendation for most product teams: build the calendar month matrix first, because it is easy to explain and to reconcile with other reports, and add a single N-day number (day 7 or day 30) for the cohorts you are actually comparing in a decision.
Calendar months alone overstate early retention for users who join late in the month and understate it for those who join early; over a full month of signups these effects partly cancel, but they do not cancel when a campaign concentrates signups in the last week. Unbounded retention is useful for products with long natural gaps (annual travel booking, tax software) and misleading for anything else.
There is a reasonable counterargument for going straight to N-day retention: it is the fairer measure and avoids explaining edge effects later. If your team already reads retention as "day 30", do that. The cost is that the matrix no longer lines up with monthly revenue or active user reports, and every reconciliation question becomes a small investigation.
Building the monthly matrix step by step
Assume an event table with one row per user action: a user_id and an event_time. If your data has several event types, filter to the cohort event and the retention event before you start. The procedure below builds a calendar month matrix.
- Load the events, parse timestamps to UTC and drop rows without a user and exact duplicates.
- Cut the data at the end of the last complete period, so a half finished month does not appear as a sudden drop.
- Find each user's first event and attach it to every row as first_time.
- Turn first_time and event_time into monthly periods: the cohort and the activity period.
- Compute the period index as the difference in months between the two.
- Count unique users per cohort and period index, and unstack into a matrix.
- Divide each row by its period 0 count to get percentages.
- Mask cells for periods the cohort has not reached yet.
Steps 1 to 5 in code:
import pandas as pd
import numpy as np
events = pd.read_csv("events.csv")
events["event_time"] = pd.to_datetime(events["event_time"], utc=True).dt.tz_localize(None)
events = events.dropna(subset=["user_id"]).drop_duplicates(["user_id", "event_time"])
events = events[events["event_time"] < "2026-11-01"]
first = events.groupby("user_id")["event_time"].min().rename("first_time")
events = events.join(first, on="user_id")
events["cohort"] = events["first_time"].dt.to_period("M")
events["period"] = events["event_time"].dt.to_period("M")
events["period_index"] = (
(events["period"].dt.year - events["cohort"].dt.year) * 12
+ (events["period"].dt.month - events["cohort"].dt.month)
)
Two details are deliberate. Timestamps are converted to UTC and then made timezone naive, because to_period drops timezone information anyway and warns about it; doing the conversion explicitly means you decide which midnight counts as the month boundary.
If your business reports in local time, convert to that zone instead of UTC before removing the timezone. And the period index is computed from year and month integers rather than by subtracting Period objects, which returns offset objects that need an extra apply step and run noticeably slower on tens of millions of rows.
Steps 6 to 8:
counts = (
events.groupby(["cohort", "period_index"])["user_id"]
.nunique()
.unstack(fill_value=0)
)
sizes = counts[0]
retention = counts.div(sizes, axis=0)
last_full = pd.Period("2026-10", freq="M")
max_idx = (last_full.year - retention.index.year) * 12 + (last_full.month - retention.index.month)
reached = pd.DataFrame(
retention.columns.values[None, :] <= np.asarray(max_idx)[:, None],
index=retention.index,
columns=retention.columns,
)
retention = retention.where(reached)
The nunique call matters: a user with 14 orders in month 2 should count once. The unstack with fill_value=0 turns missing combinations into zeros, which is correct for periods a cohort has reached and wrong for periods it has not, and that is why the last block replaces unreached cells with NaN. A September cohort has a value for period 1 (October) and nothing after it, which is what the matrix should show.
What the output looks like and how to read it
An illustrative result for a subscription app, rounded to whole percentages, with cohort sizes in the second column:
| Cohort | Users | M0 | M1 | M2 | M3 | M4 |
|---|---|---|---|---|---|---|
| 2026-06 | 4,120 | 100% | 38% | 29% | 25% | 23% |
| 2026-07 | 3,860 | 100% | 41% | 31% | 27% | |
| 2026-08 | 5,310 | 100% | 33% | 24% | ||
| 2026-09 | 4,470 | 100% | 44% |
Reading down M1, the August cohort stands out at 33 percent against 38 to 44 percent around it, and it is also the largest cohort. That pattern (bigger cohort, worse early retention) usually points to an acquisition change: a paid campaign or a promotion bringing in users with weaker intent. The September recovery to 44 percent fits an onboarding fix if one shipped in late August, or simply the end of that campaign. The matrix cannot tell you which. It tells you where to look.
Reading across rows, the decay from M1 to M3 is about 13 points for June and 14 for July, so once users survive the first month the curves look similar. Most of the action is in M0 to M1. That is common in subscription products and it shapes the decision: onboarding and first week experience matter more than late lifecycle features for this product, at least on this evidence.
To summarise many cohorts as one curve, average them weighted by size and only over cohorts that have reached each age:
avg_curve = counts.where(reached).sum() / reached.mul(sizes, axis=0).sum()
A simple mean of the column percentages gives a small cohort of 300 users the same weight as one of 5,000, and it includes or excludes cohorts inconsistently across columns. With the weighted version, M1 in the table above is (0.38 x 4,120 + 0.41 x 3,860 + 0.33 x 5,310 + 0.44 x 4,470) divided by 17,760, about 39 percent.
Mistakes that quietly distort the matrix
These come up repeatedly in reviews of retention notebooks, and most of them do not raise an error:
- Counting rows instead of users: size() or count() in place of nunique() inflates retention for heavy users and can push cells above 100 percent.
- Defining cohort size from the activity table after filtering to the retention event. If signup defines the cohort but only purchasers appear in the filtered table, every cohort shrinks to buyers and retention looks far better than it is.
- Leaving the current, incomplete month in the data. The last column of each row then shows a cliff that is only a calendar artifact.
- Filling unreached cells with zeros and then averaging them, which drags the average curve down at older ages.
- Ignoring time zones. A user active at 23:30 in Lisbon on 31 October is active at 00:30 on 1 November in Kyiv; across a large user base, a few percent of activity lands in a different month depending on the zone you pick.
- Using first event in the extracted data as the cohort event when the extract does not start at the beginning of history. Users who joined two years ago appear as new in the first month of the extract and pollute it.
- Mixing test accounts, staff and bots into the cohort. A few hundred internal users who log in daily can lift a small cohort's retention by several points.
- Comparing matrices built with different retention events across teams and calling the gap a product effect.
The extract boundary mistake deserves a fix in code rather than a note. Load first events from a full history table (or a user table with a signup date) instead of computing them from the same windowed events table, then join that onto the activity rows.
Checks before the matrix leaves your notebook
A matrix that passes these checks can be defended in a meeting. Each takes a line or two.
- Period 0 is exactly 100 percent for every cohort. If it is not, the cohort event and the activity table disagree, usually because of a filter.
- Cohort sizes add up to the number of unique users in the period you loaded. Compare sizes.sum() with events["user_id"].nunique().
- No cell exceeds 100 percent and no reached cell is NaN.
- One cohort, one cell, recomputed by hand in SQL or with a simple filter in pandas, matches to the user.
- The latest cohort's period 1 is either masked or covers a complete month.
- A known event (a release, an outage, a big campaign) shows up where you expect it in the matrix.
For an N-day version, compute each user's age in days at each event and keep only users whose window has fully elapsed before the cutoff. Without that eligibility filter, users who joined last week are counted as not retained at day 30, which pulls the latest cohort down:
events["day_index"] = (
events["event_time"].dt.normalize() - events["first_time"].dt.normalize()
).dt.days
cutoff = pd.Timestamp("2026-11-01")
eligible_ids = first[first <= cutoff - pd.Timedelta(days=35)].index
elig = events[events["user_id"].isin(eligible_ids)]
d30 = (
elig[elig["day_index"].between(28, 34)].groupby("cohort")["user_id"].nunique()
/ elig.groupby("cohort")["user_id"].nunique()
)
The 28 to 34 window is one convention for day 30 retention; some teams use exactly day 30, which is noisier for products used weekly. Whatever you choose, state it in the notebook header next to the four definitions.
For a quick visual, seaborn's heatmap with annot=True and fmt=".0%" on the retention frame (index converted to strings) works well. Keep the colour scale fixed between 0 and the highest non zero value of M1, so that later columns are not washed out.
Verdict: which matrix to ship
Pandas makes all three definitions cheap to compute. The real trade-off is between comparability and fairness. Calendar month retention is comparable with everything else the business reports and easy to explain, at the cost of edge effects for users who join at the end of a month. N-day retention treats every user the same, at the cost of a matrix that no longer reconciles with monthly reports and needs one more paragraph of explanation each time it is shown.
A second trade-off concerns where the computation lives. The pandas version is ideal for exploration and for datasets that fit in memory, which on a laptop with 16 GB usually means up to a few tens of millions of events if user_id is stored as an integer or a categorical.
Beyond that, the same logic translates almost line by line into SQL (a first event CTE, a period difference, COUNT DISTINCT grouped by cohort and age) or into DuckDB running directly on Parquet files, and the notebook keeps only the masking, weighting and plotting. Moving the heavy part out of pandas also makes the matrix reproducible by anyone with warehouse access, which matters once it starts appearing in board material.
Weekly cohorts follow the same code with to_period("W") and a week difference computed from day differences divided by 7. They respond faster to a release, and each row is roughly a quarter of the size of a monthly one, so expect 3 to 5 points of noise between neighbouring rows in a product with a few thousand signups a month.
My verdict: ship the calendar month matrix as the standing report, with unreached cells masked and a size weighted average curve underneath, and use a single N-day figure (usually day 30 in the 28 to 34 window) whenever a specific decision depends on comparing two cohorts or two variants.
Unbounded retention earns its place only when the product's natural usage gap is longer than a month. If your signups are heavily concentrated at month ends, because of billing cycles or campaign timing, flip the default and lead with N-day; in that case the calendar edge effects stop cancelling and the cheaper definition becomes the misleading one.