Get average between consecutive pairs of numpy array


Say I have a numpy array like this


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


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.

Asked By: redrobinyum



Using NumPy’s vectorized operation (highly-optimized functions for performing mathematical operations) in the code below.

arr[:-1] contains all but the last element of arr
arr[1:] contains all but the first element of arr

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
avg_arr = (arr[:-1] + arr[1:]) / 2.0

Answered By: Muhammad Saqlain

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.

Answered By: Brian61354270
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.