← All Python interview questions
Monthly active users from an event log
MediumDates & Time SeriesMicrosoftPhonePe
An event log has one row per session with a user_id and an event_time string. Product wants monthly active users — the count of distinct users per calendar month.
Write a function mau(df) that returns a Series indexed by the month as "YYYY-MM" strings, holding the distinct user count, sorted by month ascending.
This fixture runs before your code on every Run and Submit, so the data is always clean.
import pandas as pd
df = pd.DataFrame(
{
"user_id": [1, 2, 1, 3, 2, 2, 4, 1, 5],
"event_time": [
"2026-01-04 10:00",
"2026-01-19 22:10",
"2026-01-28 08:45",
"2026-02-02 12:00",
"2026-02-14 19:30",
"2026-02-27 07:05",
"2026-03-01 09:15",
"2026-03-18 16:40",
"2026-03-30 21:00",
],
}
)- Step 1: `pd.to_datetime` turns the strings into real timestamps — string slicing would work here but breaks the moment the format changes.
- Step 2: `.dt.strftime("%Y-%m")` produces the `YYYY-MM` bucket key. `.dt.to_period("M")` is the alternative when you want a Period index rather than strings.
- Step 3: Grouping by that Series (not a column name) is legal in pandas as long as its index aligns with the frame.
- Step 4: `.nunique()` counts *distinct* users, so user 2's three February sessions count once. Using `.count()` here is the classic mistake — that returns sessions, not users.
- Step 5: `.sort_index()` puts the months in chronological order, which zero-padded `YYYY-MM` strings sort correctly.
import pandas as pd
def mau(df):
parsed = pd.to_datetime(df["event_time"])
month = parsed.dt.strftime("%Y-%m")
return df.groupby(month)["user_id"].nunique().sort_index()Learn the concept first
Stuck on Dates & Time Series? These free Python lessons teach it step by step.
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