Skip to content
Advertisement

Averaging over every n elements of a numpy array

I have a numpy array. I want to create a new array which is the average over every consecutive triplet of elements. So the new array will be a third of the size as the original.

As an example:

 np.array([1,2,3,1,2,3,1,2,3])

should return the array:

 np.array([2,2,2])

Can anyone suggest an efficient way of doing this? I’m drawing blanks.

Advertisement

Answer

If your array arr has a length divisible by 3:

np.mean(arr.reshape(-1, 3), axis=1)

Reshaping to a higher dimensional array and then performing some form of reduce operation on one of the additional dimensions is a staple of numpy programming.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement