[Numpy-discussion] moving window product
Warren Weckesser
warren.weckesser@enthought....
Mon Mar 21 13:19:18 CDT 2011
On Mon, Mar 21, 2011 at 12:10 PM, Brent Pedersen <bpederse@gmail.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.
> like::
>
> 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)
return windowed_view
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:"
print w
p = w.prod(axis=-1)
print "windowed products:", p
-----
Warren
> thanks,
> -brent
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110321/1da8e3c9/attachment.html
More information about the NumPy-Discussion
mailing list