PythonMastery
Python programs · Useful programs · intermediate

Rolling average (moving average) in Python

Compute a moving average over a window of values, such as a 3-day average temperature, with a running total that keeps the program fast.

A rolling average (or moving average) is the average of the last few values, recalculated as the window moves along the data. A 3-day rolling average of temperatures smooths out single hot or cold days.

The program

python
def rolling_average(values, window):
    if window < 1:
        raise ValueError("window must be at least 1")
    averages = []
    total = 0
    for i, value in enumerate(values):
        total += value
        if i >= window:
            total -= values[i - window]  # the value that just left the window
        if i >= window - 1:
            averages.append(total / window)
    return averages


temperatures = [21, 23, 22, 25, 27, 26, 24]
for avg in rolling_average(temperatures, 3):
    print(round(avg, 2))

print(rolling_average([5, 6], 3))
output
22.0
23.33
24.67
26.0
25.67
[]

How it works

Another way: slicing

The shortest version adds up each slice of the list:

python
def rolling_average(values, window):
    return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]


print([round(avg, 2) for avg in rolling_average([21, 23, 22, 25, 27, 26, 24], 3)])
output
[22.0, 23.33, 24.67, 26.0, 25.67]

This is easier to read, and fine for short lists. But it adds up window numbers for every average, so for a window of 1,000 days it does about 1,000 times more work than the running-total version.

Learn the idea: Lists & Sequences, Loops: for, while, and the Pythonic Patterns