Skip to main content

From a transactions table with customer_id, date and amount, compute a 7-day rolling average of daily spend for each customer. For example, a customer who spends 100, 200 and 300 on three days in a row has a rolling average of 200 on the third day.

Coding rounds · Intermediate 2

Short answer

Sum to one row per customer and day, sort by date, set date as the index, then use a time-based window inside each group: groupby("customer_id")["amount"].rolling("7D").mean(). "7D" means 7 calendar days, while rolling(7) means 7 rows. Sorting dominates at O(n log n).

Deeper answer

First clarify the definition. Ask whether several transactions on one day should be summed first, whether days with no spend count as zero or are ignored, and whether the window includes the current day. Check that date is a real datetime column, not text.

The steps are: convert with pd.to_datetime(df["date"]). Sum per day with daily = df.groupby(["customer_id", "date"], as_index=False)["amount"].sum(). Then run daily.sort_values("date").set_index("date").groupby("customer_id")["amount"].rolling("7D").mean(). The "7D" window covers the current day and the six days before it, and it averages only the days that have rows. If missing days must count as zero, fill them first with resample("D").sum() inside each customer and then use rolling(7, min_periods=1).

The result has a two-level index of customer and date, so call reset_index() before joining it back. Test a customer with a gap of a week, a customer with one row, and two transactions on the same day. Say why rolling(7) alone is wrong with gaps: it counts rows, so it can reach back many weeks.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Tables with pandas

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.