Averaging over every n elements of a numpy array

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.

Leave a Comment