Practice / window functions

Three-Day Moving Average

hard

A food truck logs daily sales and wants a smoothed trend line: a trailing three-day moving average.

daily

day is the day number since launch. Day 3 is missing — the truck was closed — so the recorded days are 1, 2, 4, 5.

Your task: return day, sales, and a moving_avg — the average sales over the current row and the two rows before it in day order (a trailing three-row window, counted by rows, not by calendar days). Early rows average over however many rows exist: day 1 is just itself, day 2 averages two.

Assign your answer DataFrame to result. Row order doesn't matter.

dailyinput DataFrame

Schema
columntype
daylong
salesdouble
Sample rows
daysales
16
29
412
53
Expected output shape
daysalesmoving_avg· 4 rows
Hint

Window.orderBy("day").rowsBetween(-2, 0), then F.avg("sales").over(w). rowsBetween counts rows, not calendar days — so a missing day still reaches back to the previous three recorded rows.

Lesson refresher

This problem builds on Window Functions (~9 min). Pop it open in a new tab if you want a quick recap.

Loading editor…
Hit Run to execute your code and see the output here.