[Numpy-discussion] moving window product
Mon Mar 21 13:19:18 CDT 2011
On Mon, Mar 21, 2011 at 12:10 PM, Brent Pedersen <email@example.com> wrote:
> hi, is there a way to take the product along a 1-d array in a moving
> window? -- similar to convolve, with product in place of sum?
> currently, i'm column_stacking the array with offsets of itself into
> window_size columns and then taking the product at axis 1.
> w = np.column_stack(a[i:-window_size+i] for i in range(0, window_size))
> window_product = np.product(w, axis=1)
> but then there are the edge effects/array size issues--like those
> handled in np.convolve.
> it there something in numpy/scipy that addresses this. or that does
> the column_stacking with an offset?
Here's a quick demo of how you might use the function as_strided from the
stride_tricks module to do this.
import numpy as np
from numpy.lib.stride_tricks import as_strided
def moving_window(x, length, step=1):
# Assume x is a 1D ndarray
r = (x.size - length + step) / step
nb = x.itemsize
strides = (step*nb, nb)
windowed_view = as_strided(x, shape=(r, length), strides=strides)
if __name__ == "__main__":
x = np.linspace(0,4.0,21)
print "x =", x
w = moving_window(x, length=4, step=2)
print "windowed view of x:"
p = w.prod(axis=-1)
print "windowed products:", p
> NumPy-Discussion mailing list
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion