Rolling Window Calculations
Pandas data engineering interview problem. Difficulty: beginner. Pattern: Window Functions. About 12 minutes. Free to practice.
7-day rolling average and 30-day rolling sum on a short series. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A rolling (or moving) value looks at the last few rows to smooth out noise. A 7-day rolling average is the average of the current day and the 6 days before it. A 30-day rolling sum adds up the current day and the 29 days before it. At the start of the series there are fewer days than the window size, and min_periods=1 tells pandas to use what exists instead of giving NaN. Sort the table by date. Add 2 columns: rolling_avg_7d, the rolling mean of value with a window of 7, and rolling_sum_30d, the rolling sum of value with a window of 30, both with min_periods=1. Return date, value and the two new columns, and store the table in result. The editor builds df and ends with result = df. Change that last line.
Requirements
- Sort the table by date first.
- Add rolling_avg_7d with rolling(7, min_periods=1).mean().
- Add rolling_sum_30d with rolling(30, min_periods=1).sum().
- Return date, value, rolling_avg_7d, rolling_sum_30d in result.
Constraints
- The table has 6 days, one value per day, so no window ever has more than 6 rows.
- Use min_periods=1, so there is a value from the first row on.
- Rolling windows count rows, so the data must be sorted before you use them.
Examples
Input: daily values Output: date | value | rolling_avg_7d | rolling_sum_30d 2024-01-01 | 1.0 | 1.0 | 1.0 2024-01-02 | 2.0 | 1.5 | 3.0 2024-01-03 | 3.0 | 2.0 | 6.0 2024-01-04 | 4.0 | 2.5 | 10.0 2024-01-05 | 5.0 | 3.0 | 15.0 2024-01-06 | 6.0 | 3.5 | 21.0 Short fixture never fills a full 7/30 window; min_periods=1 still progresses.
Topics: lakebench, pandas, rolling.
More interview problems · All interview problems · Learn data engineering
Rolling Window Calculations
Interview-style drill: 7-day rolling average and 30-day rolling sum on a short series.
Sort by `date`. Add `rolling_avg_7d` = rolling mean of `value` with window 7 and `rolling_sum_30d` with window 30, both `min_periods=1`. Return `date`, `value`, and both rolling columns. Assign `result`.