Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get average between consecutive pairs of numpy array

Say I have a numpy array like this

[1,2,3,4,5]

I want to generate an array that is the equal to the average of consecutive elements

[1.5,2.5,3.5,4.5]

Is there any efficient way to do this outside of just iterating through?

I'm not really sure what to do because reshaping doesn't really work and I'm trying to get a smaller array.

like image 569
redrobinyum Avatar asked Feb 13 '26 13:02

redrobinyum


1 Answers

You can use np.convolve to implement two-element averaging as the convolution of the input vector with the vector [0.5, 0.5]:

>>> a = [1, 2, 3, 4, 5]
>>> np.convolve(a, [0.5, 0.5], "valid")
array([1.5, 2.5, 3.5, 4.5])

np.convolve is a highly optimized routine, and will delegate to different implementations depending on what it estimates will be fastest for the given inputs. For small vectors like [0.5, 0.5] it will likely just compute the result directly (0.5*a[n] + 0.5*[n+1] for each element), but for large inputs it can leverage FFT-based convolution algorithms to compute the result with significantly fewer operations than the direct method.

like image 98
Brian Avatar answered Feb 15 '26 01:02

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!