Start learning free

LESSON 109 OF 165 · MACHINE LEARNING: TIME SERIES

Smooth It: Rolling Averages in Python

Practice

Weekly revenue is noisy: a good week, then a quiet one, and the trend is hard to see. A rolling average gives each week the average of a small window of weeks: that week and the few before it. The window slides down the series one row at a time, so one odd week only moves the average a little.

series.rolling(n) sets up a window of n rows that ends on each row, and .mean() after it gives back a Series of the same length with each window's average. The first n − 1 rows have no full window, so they get NaN, pandas' mark for a missing value.

visits = pd.Series([10, 20, 30, 70])
avg = visits.rolling(3).mean()
# NaN, NaN, 20.0 = (10 + 20 + 30) / 3, 40.0 = (20 + 30 + 70) / 3

pd.DataFrame({"a": s1, "b": s2}) gives back a table with the two Series as columns, lined up by their labels. series.isna() gives back True for each NaN, and .sum() counts the Trues.

Your program must print:

            revenue  smooth
date                       
2026-01-04       23     NaN
2026-01-11      215     NaN
2026-01-18       16     NaN
2026-01-25        0   63.50
2026-02-01      298  132.25
2026-02-08      109  105.75
            revenue   smooth
date                        
2026-11-01     3110  2593.75
2026-11-08     3549  2950.50
2026-11-15     3200  3137.75
2026-11-22     2671  3132.50
2026-11-29     3090  3127.50
Weeks without an average: 3

Your task: the starting code builds weekly, the paid revenue per week. Below the blank line, make smooth, each week's average with the three weeks before it, put weekly and smooth side by side in table as the columns "revenue" and "smooth", print its first 6 and last 5 rows, then print how many weeks have no average.


Assignment
Follow the Coding Tutorial to smooth the weekly revenue with a 4-week rolling average and print it next to the raw numbers.


Hint
The window ends on the week itself: the first average, for 2026-01-25, is (23 + 215 + 16 + 0) / 4 = 63.50. The three weeks before it have fewer than 4 weeks to average, so they show NaN.


STEP 1 OF 5
    Ctrl + Enter to check

    Ts Rolling in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free