← All Python interview questions
Build a monthly cohort retention matrix
HardPandas — GroupBySwiggyCred
Growth wants classic cohort retention: users grouped by their signup month, then counted by how many months later they were still active.
Write retention(df) that returns a DataFrame indexed by signup month period, with integer month offsets as columns and the count of distinct active users in each cell (0 where nobody returned).
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
activity = pd.DataFrame({
"user_id": [1, 1, 1, 2, 2, 3, 4, 4, 5],
"signup_month": pd.to_datetime([
"2026-01-01", "2026-01-01", "2026-01-01",
"2026-01-01", "2026-01-01",
"2026-01-01",
"2026-02-01", "2026-02-01",
"2026-02-01",
]).to_period("M"),
"active_month": pd.to_datetime([
"2026-01-15", "2026-02-10", "2026-03-05",
"2026-01-20", "2026-03-11",
"2026-01-25",
"2026-02-14", "2026-03-19",
"2026-02-27",
]).to_period("M"),
})- Step 1: Subtracting two `Period` values gives an offset object; `.n` pulls out the integer number of months, which is the column axis of every cohort chart.
- Step 2: `aggfunc='nunique'` counts distinct users — a user with three visits in month 2 must still count once.
- Step 3: `fill_value=0` renders 'nobody came back' as a zero rather than a hole in the triangle.
- Step 4: Sorting both axes gives the familiar upper-triangular shape where each row starts at offset 0.
def retention(df):
out = df.copy()
out["offset"] = (out["active_month"] - out["signup_month"]).apply(lambda x: x.n)
matrix = out.pivot_table(
index="signup_month",
columns="offset",
values="user_id",
aggfunc="nunique",
fill_value=0,
)
matrix.columns.name = None
return matrix.sort_index().sort_index(axis=1)Learn the concept first
Stuck on Pandas — GroupBy? These free Python lessons teach it step by step.
More Pandas — GroupBy questions
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program