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
- The first window is days 1 to 3: (21 + 23 + 22) / 3 = 22.0. The next window is days 2 to 4: (23 + 22 + 25) / 3 = 23.33.
- Instead of adding up the whole window each time, the program keeps a running
total. Each new value is added, and the value that falls out of the window is subtracted. - An average is saved only once the window is full, from position
window - 1onwards. - 7 values with a window of 3 give 5 averages. A list shorter than the window gives an empty list.
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.