Chapter 9 — Cohorts and Product Economics

From Raw Events to a Cohort

16 min

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_idevent_timeevent_type
172184-01-05 14:02signup
172184-01-08 09:41purchase
182184-01-08 20:15signup
172184-01-15 11:07purchase

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 cadet studies a hologram that transforms raw user events into weekly cohorts while a robot cat watches from the side.
The choice of first event determines both cohort membership and cohort date, while empty future periods for newer cohorts mean there are no observations yet, not zero activity.

A is a group of users whose chosen starting event occurred in the same period. Defining a cohort always requires two decisions:

  1. which event counts as the start — signup, first purchase, or first login after installation;
  2. 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–13 from 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.

raw eventsready to pivotuser_idevent_timeA01-03A01-11B01-09C01-16D01-24A has two events → two rows1) first event2) cohort week3) age =event week− cohort weekusercohortageAW010AW011BW020CW030DW040row = (user, age) — only the pivot is left
Three steps take us from raw events to rows shaped like (user, cohort, age): the first occurrence of the chosen starting event fixes the user’s cohort for the calculation, while age is recalculated for each later event.

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_idweekcohort_weekage_w
172184-01-052184-01-050
172184-01-122184-01-051
182184-01-122184-01-120

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.

  • 0 means “this period was observed, but nobody returned” — a fact about the product;
  • NaN means “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.

Kotomarket’s raw log is already in 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.
python · pandas
Practice: write the code
Investigator, build the cohorts yourself. Using the events log, create cohorts by first purchase (purchase events) with a weekly step, and calculate three values:
  1. cohort_sizes — a list of cohort sizes in chronological order (unique buyers at age 0);
  2. max_age — the maximum observed age in weeks across the whole log;
  3. 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.
The third value checks for the mine: if it is greater than 1, the log really does contain users with multiple purchases in the same week, so using count instead of nunique would overstate retention.
python · pandas
Practice: write the code
Now check how much the choice of starting event matters. Build cohorts TWICE from the same log:
  1. n_cohorts_purchase — the number of weekly cohorts when the start is first purchase;
  2. n_cohorts_signup — the number when the start is signup (signup);
  3. moved_users — the number of users who land in DIFFERENT weeks under the two definitions.
If moved_users is a noticeable share of the 420 buyers, then “retention 45%” really does mean very little unless the starting event is specified.
python · pandas
Check yourself
A colleague builds cohorts by signup but defines a return as a purchase. They define cohort size as the number of users who made a purchase at age 0. What’s wrong with that?
Check yourself
The log was exported on Tuesday. In the matrix, every cell to the right of age 0 is empty for the newest cohort. What should you do before averaging retention across cohorts?
Key takeaways
  • The data doesn’t contain cohort and age columns — 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, NaN means “not observed.” If that age has already occurred but nobody returned, the result is zero. Don’t replace every missing value with fillna(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.