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:
| row | store | date | sales |
|---|---|---|---|
| 0 | A | 2024-03-01 | 10 |
| 1 | A | 2024-03-02 | 12 |
| 2 | A | 2024-03-03 | 14 |
| 3 | A | 2024-03-04 | 16 |
| 4 | A | 2024-03-05 | 18 |
| 5 | B | 2024-03-01 | 100 |
| 6 | B | 2024-03-02 | 110 |
| 7 | B | 2024-03-03 | 120 |
| 8 | B | 2024-03-04 | 130 |
| 9 | B | 2024-03-05 | 140 |
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?