平均numpy数组的每n个元素 [英] Averaging over every n elements of a numpy array
本文介绍了平均numpy数组的每n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个numpy数组.我想创建一个新数组,该数组是元素的每个连续三元组的平均值.因此,新数组将是原始数组大小的三分之一.
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.
例如:
np.array([1,2,3,1,2,3,1,2,3])
应返回数组:
np.array([2,2,2])
有人可以建议这样做的有效方法吗?我在画空白.
Can anyone suggest an efficient way of doing this? I'm drawing blanks.
推荐答案
如果数组arr
的长度可被3整除,则为
If your array arr
has a length divisible by 3:
np.mean(arr.reshape(-1, 3), axis=1)
重塑为高维数组,然后对其中一个附加维执行某种形式的归约运算是numpy编程的主要内容.
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数组的每n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文