From Raw Events to a Cohort
A cohort starts with choosing an event
Vault-9, 2184. Kotomarket’s black box has been opened, and the first thing the investigator sees is neither a finished matrix nor a colorful heatmap. It’s a raw event log:
| user_id | event_time | event_type |
|---|---|---|
| 17 | 2184-01-05 14:02 | signup |
| 17 | 2184-01-08 09:41 | purchase |
| 18 | 2184-01-08 20:15 | signup |
| 17 | 2184-01-15 11:07 | purchase |
There’s no “” column and no “week of life” column. Those fields aren’t present in the source data; the analyst creates them. The choices made at this stage shape every conclusion that follows in this chapter.
QUERY: Every beautiful cohort view of the world starts with a table that doesn’t contain the word “cohort” at all. I checked. Repeatedly.

A is a group of users whose chosen starting event occurred in the same period. Defining a cohort always requires two decisions:
- which event counts as the start — signup, first purchase, or first login after installation;
- which time step to use — day, week, or month.
Decision one: signup or first purchase
This may seem like a minor detail, but it changes the question the analysis answers.
- A signup cohort answers: “How well does the journey from account creation to habit formation work?” The denominator includes everyone who created an account, including people who never buy anything. If return activity is measured through purchases, non-buyers still remain in the denominator and lower the metric. For example, if half of registered users never become buyers, you can’t directly compare that cohort’s with retention among buyers.
- A first-purchase cohort answers: “How well does the product retain people who have already paid?” The denominator includes buyers only. The metric may be higher, but that doesn’t mean the product improved; you’re looking at a different population and answering a different question.
Some cat owners signed up early: they browsed, added food to their carts, and waited until the following week to buy. For those users, signup week and first-purchase week are different, so they belong to different cohorts under the two definitions. You’ll count them yourself in the exercise; spoiler: there are enough to change the picture.
Investigator’s rule: choose the starting event before you calculate the metric, and state that choice explicitly in the metric definition. “Retention 45%” without “first-purchase cohort, weekly step” is incomplete, just like “churn 5%” in a later lesson.
L., entry #28: I asked marketing which event their retention was based on. They said, “The usual one.” Three reports, three different definitions, none written down.
Decision two: calendar grid or rolling window
There are two ways to measure a user’s age.
- Calendar-based — this is the approach we use in this chapter. The calendar is divided into Monday-through-Sunday weeks. A user’s cohort is determined by the week of the first event, and age shows how many calendar weeks have passed. Advantage: cells from the same calendar week line up diagonally in the matrix, which makes releases and incidents visible. Drawback: a user who arrives on Sunday has only part of that day in week 0.
- Rolling from the start date (
day 0–6,day 7–13from each user’s own start date): every user has their own calendar. Advantage: everyone gets windows of equal length. Drawback: the same calendar event can fall into different age windows for different users, so its effect gets spread across the matrix and the diagonal no longer maps to one exact calendar week.
Both approaches are valid, but they answer different questions. We’ll use calendar weeks because we’re investigating the company’s history, where the timing of incidents, releases, and promotions matters.
Three steps to build the cohort table
First, keep only the events that define the in ev. In this lesson, those are purchases, so the first event in ev for each user is that user’s first purchase.
Step 1. Calendar week of the event.
ev["week"] = ev["event_time"].dt.to_period("W").dt.start_time
to_period("W") maps a point in time to a Monday-through-Sunday weekly period, and .dt.start_time returns the start of that period — Monday — as a regular Timestamp. These values are convenient to subtract. For monthly grouping, use to_period("M"), but then age must also be measured in months: dividing days by 7 only makes sense for weekly cohorts.
Step 2. Week of each user’s first purchase.
first = ev.groupby("user_id")["week"].min()
Because ev now contains only purchases, min() finds the week of each user’s first purchase. The result contains exactly one value per user. Before joining it back, name it cohort_week with .rename("cohort_week"), as shown in the practice block below.
A cohort is assigned once and then stays fixed, much like a graduation year. Next, attach it back to every event for that user with a merge on user_id. This is the same many-to-one relationship you saw in the archive-joining chapter: many rows on the left, exactly one row per user on the right, so the rows on the left do not multiply.
Step 3. Cohort age.
ev["age_w"] = (ev["week"] - ev["cohort_week"]).dt.days // 7
Subtracting two dates gives a Timedelta; .dt.days gives the number of days, and integer division by 7 gives the number of weeks. Age 0 is the week of the first purchase, age 1 is the next calendar week, and so on. Negative ages should never appear. If they do, cohort_week was either not calculated as the minimum week over the same event set or was joined incorrectly.
After these three steps, the table looks like this:
| user_id | week | cohort_week | age_w |
|---|---|---|---|
| 17 | 2184-01-05 | 2184-01-05 | 0 |
| 17 | 2184-01-12 | 2184-01-05 | 1 |
| 18 | 2184-01-12 | 2184-01-12 | 0 |
This is the finished table that a single pivot_table call will turn into the matrix in the next lesson. The hardest part is already behind you.
Mine #1: events ≠ people
One cat owner might order food on Monday and treats on Thursday, creating two rows in the same week. If you count rows, the number of “returning users” can exceed the number of people in the cohort. From here on, use nunique() on user_id, not count(). In the next lesson, you’ll see exactly how count() distorts .
Mine #2: immature cohorts
The log ends on a specific date. A cohort that first appeared in the final week of the log could not have reached age 1 because the next calendar week is not in the data yet. Right censoring is the situation where the observation window ends before later periods can be observed.
0means “this period was observed, but nobody returned” — a fact about the product;NaNmeans “this period could not have been observed yet” — a fact about the data.
A simple pivot_table built from purchase rows cannot distinguish these cases by itself: both no purchases in an already available period and an age that is not yet available may initially appear as missing values. Use the log’s end date to separate them: convert missing values in observable periods to 0, but leave immature cells as NaN.
Confusing the two is a common mistake. Unconditional fillna(0) before averaging pushes retention down for young cohorts and makes the product appear to be deteriorating even though only the observation windows differ. This is the same issue you saw with unfinished periods in the investigation-method chapter: an incomplete period should not be compared with a complete one.
L., entry #28 (continued): The presentation showed 0% retention for the latest cohort. The cohort had existed for four days.
events (user_id, event_time, event_type). Build the three steps yourself: first event → cohort week → age. Watch an unstructured event log turn into a cohort table.events log, create cohorts by first purchase (purchase events) with a weekly step, and calculate three values:
cohort_sizes— a list of cohort sizes in chronological order (unique buyers at age 0);max_age— the maximum observed age in weeks across the whole log;rows_vs_users_w0— the ratio of the NUMBER OF ROWS to the number of UNIQUE users at age 0 in the very first cohort.
count instead of nunique would overstate retention.n_cohorts_purchase— the number of weekly cohorts when the start is first purchase;n_cohorts_signup— the number when the start is signup (signup);moved_users— the number of users who land in DIFFERENT weeks under the two definitions.
moved_users is a noticeable share of the 420 buyers, then “retention 45%” really does mean very little unless the starting event is specified.Key takeaways
- The data doesn’t contain
cohortandagecolumns — the analyst creates them. A definition combines a starting event with a time step; write both choices next to the metric in plain language. - Signup and first purchase are different cohort starts. They can change the denominator, the population, and the final result; at Kotomarket, 141 out of 420 buyers land in different weeks.
- Three build steps: week of the chosen event (
to_period('W').dt.start_time) → user’s first such event (groupby().min()+merge) → age ((week - cohort_week).dt.days // 7). - Events ≠ people. One buyer can produce several rows in a week, so count users with
nunique(). NaN≠ 0. If a cohort hasn’t lived long enough to reach a given age,NaNmeans “not observed.” If that age has already occurred but nobody returned, the result is zero. Don’t replace every missing value withfillna(0)indiscriminately: that turns a young cohort into apparent product deterioration.
The (user_id, cohort, age) table is ready. In the next lesson, one line with pivot_table will turn it into a matrix, and you’ll learn how to read it.