对numpy数组的每n个元素求平均值
16lz
2021-01-22
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编程的主要内容。
更多相关文章
- [置顶] Python + C/C++ 嵌入式编程(1):多维数组Numpy.Array(
- Python根据第一项从2d数组中删除元素
- linux中awk数组应用域替换
- 文本文件到字符串数组?
- 将现有数组中的所有元素传递给xargs
- postgresql 数组 多了引号 空格处理
- PB怎么将动态的sql语句以及数组。传给datawindow。
- PostgreSQL: array 数组类型添加元素 数组的使用
- 避免在Java接口中使用数组的3个理由