Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading