Averaging over every n elements of a numpy array

空扰寡人 提交于 2019-12-17 17:45:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15956309/averaging-over-every-n-elements-of-a-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!