Get average between consecutive pairs of numpy array

Advertisements

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.

>Solution :

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

print(avg_arr)

Leave a ReplyCancel reply