Build a monthly cohort retention matrix with pandas

HardpandasPro

Why it matters Cohort retention matrices are the main health chart for subscription and consumer AI products.

A cohort matrix shows, for users who joined in each month, what share was still active 0, 1, 2 ... months later. It is the standard picture of whether a product keeps its users.

Write retention_matrix(events) where events has columns user_id (int) and month ('YYYY-MM' string), one row per activity (a user can have many rows in one month).

A user's cohort is their earliest month. offset = months between the activity month and the cohort month. Let K be the largest offset in the data. Return a DataFrame with columns exactly ['cohort', 'm0', 'm1', ..., 'mK']: one row per cohort (as 'YYYY-MM'), sorted ascending, plain 0..n-1 index, where mk is the fraction of the cohort's users with at least one activity at offset k (0.0 if none). m0 is always 1.0.

Signaturedef retention_matrix(events)

Example

user 1 active 2026-01, 2026-01, 2026-02; user 2 active 2026-01; user 3 active 2026-02. Result: cohort ['2026-01', '2026-02'], m0 [1.0, 1.0], m1 [0.5, 0.0].

Understand the idea

A cohort is a group of users who started in the same period. A retention matrix has one row per cohort and one column per period since start; each cell is the share of that cohort active in that period. It separates 'we got many new users' from 'we kept our users'.

Worked example: users 1 and 2 start in Jan, user 3 in Feb. In Jan cohort, both are active at offset 0 (1.0) and only user 1 at offset 1 (1 of 2 = 0.5). Feb cohort has user 3 at offset 0 (1.0) and nobody at offset 1 (0.0).

Rule: month index = year * 12 + month. cohort(u) = min index of u. offset = index - cohort. cell(c, k) = distinct users of cohort c active at offset k / users in cohort c.

Growth and finance teams for AI apps read this matrix every month.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleretention_matrix(_d1()).to_dict('list')
  • Sample 2: three cohorts across a year endretention_matrix(_d2()).to_dict('list')