I have a numpy array. I want to create a new array which is the average over every third element. So the new array will be a third of the size as the original.
我有一个numpy数组。我想创建一个新数组,它是每三个元素的平均值。因此,新阵列将是原始阵列的三分之一。
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 个解决方案
#1
46
If your array arr
has a length divisible by 3:
如果你的数组arr的长度可被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.
重塑为更高维度的阵列,然后在其中一个附加维度上执行某种形式的缩减操作是numpy编程的主要内容。
#1
46
If your array arr
has a length divisible by 3:
如果你的数组arr的长度可被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.
重塑为更高维度的阵列,然后在其中一个附加维度上执行某种形式的缩减操作是numpy编程的主要内容。