Averaging over every n elements of a numpy array

user1654183 picture user1654183 · Apr 11, 2013 · Viewed 33.3k times · Source

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.

Answer

Jaime picture Jaime · Apr 11, 2013

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.