Trailing Three-Month Sales, Excluding the Latest Month
Problem
You are given a DataFrame `sales`.
```text
+----------+--------+---------+
| Column | Type |
+----------+--------+
| store_id | int |
| period | int |
| revenue | int |
+----------+--------+
(store_id, period) is the unique key.
```
For each store, compute a trailing three-period sum of `revenue` (the current period plus the two preceding periods, ordered by `period`). Then **drop each store's most recent period** and report the rest. Return columns `store_id`, `period`, `revenue` (where `revenue` is now the trailing sum), ordered by `store_id` ascending and `period` descending.
Input data
Example rows — the live problem includes the full dataset.
| store_id | period | revenue |
|---|---|---|
| 1 | 1 | 20 |
| 1 | 2 | 30 |
| 1 | 3 | 40 |
| 2 | 1 | 90 |
Expected output
Your answer should return 2 rows with the columns store_id, period, revenue.
Starter code (Pandas (Python))
import pandas as pd
def trailing_sales(sales: pd.DataFrame) -> pd.DataFrame:
# Your code here
return salesSolve this Pandas question free
Write Pandas (Python) and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock