How to compute rolling/moving window average of a NumPy array

The best way to compute the moving average for a NumPy array is to use bn.move_mean()  from the bottleneck library. First, install bottleneck using

pip install bottleneck

Now import it using

import bottleneck as bn

Now you have to decide what to do with windows at the beginning of the array where not enough elements are present. The default behaviour is to set the result to NaN for those windows:

x = [1,2,3,4,5,6]
result = bn.move_mean(x, window=3)
# result = [nan, nan,  2.,  3.,  4.,  5.]

but you can also accept any window even if it has less than window elements.

x = [1,2,3,4,5,6]
result = bn.move_mean(x, window=3, min_count=1)
# result = [1. , 1.5, 2. , 3. , 4. , 5. ]

Another example with window=4:

x = [1,2,3,4,5,6]
result = bn.move_mean(x, window=4, min_count=1)
# result = array([1. , 1.5, 2. , 2.5, 3.5, 4.5])