AnalystPath

Trailing Three-Month Sales, Excluding the Latest Month

PandasHardSenior level~10 min

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.

sales
store_idperiodrevenue
1120
1230
1340
2190

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 sales

Solve 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

Related Pandas questions