c00kiemonster - 11 months ago 60

Python Question

Is there a way to efficiently implement a rolling window for 1D arrays in Numpy?

For example, I have this pure Python code snippet to calculate the rolling standard deviations for a 1D list, where

`observations`

`n`

`stdev = []`

for i, data in enumerate(observations[n-1:]):

strip = observations[i:i+n]

mean = sum(strip) / n

stdev.append(sqrt(250*sum([(s-mean)**2 for s in strip])/(n-1)))

Is there a way to do this completely within Numpy, i.e., without any Python loops? The standard deviation is trivial with

`numpy.std`

I found this blog post regarding a rolling window in Numpy, but it doesn't seem to be for 1D arrays.

Answer

Just use the blog code, but apply your function to the result.

i.e.

```
numpy.std(rolling_window(observations, n), 1)
```

where you have (from the blog):

```
def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
```

Source (Stackoverflow)