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.
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)