You have a users frame with a signup month and an activity frame with the months each user was active. Growth wants month-1 retention per cohort: the share of a cohort that was active in the month immediately after signup.
Write a function retention(users, activity) that returns a dictionary mapping each signup_month (an integer) to the retention rate as a float rounded to 2 decimals. Months are simple integers, so month 1 is followed by month 2.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
users = pd.DataFrame(
{
"user_id": [1, 2, 3, 4, 5, 6, 7],
"signup_month": [1, 1, 1, 1, 2, 2, 2],
}
)
activity = pd.DataFrame(
{
"user_id": [1, 1, 2, 3, 3, 5, 6, 6, 7],
"active_month": [1, 2, 2, 1, 3, 2, 2, 3, 4],
}
)- Step 1: Left-merge activity onto users so a user with no activity at all still appears — dropping them would inflate the retention rate.
- Step 2: Flag each activity row with `active_month == signup_month + 1`. Users with no activity get `NaN` in `active_month`, and that comparison is `False`, which is exactly right.
- Step 3: Collapse to one row per user with `groupby([...]).max()` on the boolean — `max` of booleans is a logical OR, so a user counts once no matter how many qualifying sessions they had.
- Step 4: Average the per-user flags within each cohort. The mean of booleans *is* the retention rate.
- Step 5: Round to 2 decimals and cast the keys and values to plain Python types so the dict is easy to serialise.
import pandas as pd
def retention(users, activity):
joined = users.merge(activity, on="user_id", how="left")
joined["retained"] = joined["active_month"] == joined["signup_month"] + 1
per_user = joined.groupby(["user_id", "signup_month"], as_index=False)["retained"].max()
rates = per_user.groupby("signup_month")["retained"].mean().round(2)
return {int(k): float(v) for k, v in rates.items()}Learn the concept first
Stuck on Pandas — Joins? These free Python lessons teach it step by step.
More Pandas — Joins questions
Asked at Google
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