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

install_bottleneck.sh
pip install bottleneck

Now import it using

import_bottleneck.sh
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:

moving_average_examples.py
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.

example.py
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:

example.py
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])

 


Check out similar posts by category: Python