[Numpy-discussion] Rolling window (moving average, moving std, and more)

Keith Goodman kwgoodman at gmail.com
Mon Jan 3 10:32:44 EST 2011


On Fri, Dec 31, 2010 at 8:29 PM, Erik Rigtorp <erik at rigtorp.com> wrote:

> Implementing moving average, moving std and other functions working
> over rolling windows using python for loops are slow. This is a
> effective stride trick I learned from Keith Goodman's
> <kwgoodman at gmail.com> Bottleneck code but generalized into arrays of
> any dimension. This trick allows the loop to be performed in C code
> and in the future hopefully using multiple cores.

I like using strides for moving window functions. The one downside I
found is that it is slow when window * (arr.shape[axis] - window) is
large:

>> a = np.random.rand(1000000)
>> b = rolling_window(a, 5000)

>> import bottleneck as bn
>> timeit bn.nanmean(b, axis=1)
1 loops, best of 3: 7.1 s per loop
>> timeit bn.move_nanmean(a, window=5000, axis=0)
100 loops, best of 3: 7.99 ms per loop



More information about the NumPy-Discussion mailing list