Skip to content
ML Academy

S06 · interview simulation

Python gym: entity-safe lag and rolling features in pandas

People, data and outputs in this scenario are simulated. Each stage is recorded when you commit; the reveal comes after.

  • 5stages
  • 30 minabout
  • 0stages committed

The brief

Simulated interviewer: "You have daily sales per store in a DataFrame df with columns store, date (datetime64) and sales. Add roll3_prev: the mean of the same store's sales over the previous days (up to 3, excluding today). This feeds a next-day forecast." The fixture is synthetic:

rowstoredatesales
0A2024-03-0110
1A2024-03-0212
2A2024-03-0314
3A2024-03-0416
4A2024-03-0518
5B2024-03-01100
6B2024-03-02110
7B2024-03-03120
8B2024-03-04130
9B2024-03-05140

This is a structured task: you choose and justify; no code is executed in the app. The outputs quoted were produced with pandas 3.0.6.

Stage 1 of 5

Candidates:

# (a)
df["roll3_prev"] = df["sales"].shift(1).rolling(3, min_periods=1).mean()
# (b)
df["roll3_prev"] = df.groupby("store")["sales"].shift(1).rolling(3, min_periods=1).mean()
# (c)
df["roll3_prev"] = df.groupby("store")["sales"].transform(
    lambda s: s.shift(1).rolling(3, min_periods=1).mean())
# (d)
df["roll3_prev"] = df.groupby("store")["sales"].rolling(3).mean()

Which candidate is correct on this (sorted, gap-free) fixture?

Sign in to play scenarios (answers are recorded before the reveal).