总结numpy的阵列通过总结 [英] Aggregate Numpy Array By Summing
问题描述
我有形状的numpy的阵列(4320,8640)
。我想有形状的阵列(2160,4320)
。
I have a Numpy array of shape (4320,8640)
. I would like to have an array of shape (2160,4320)
.
您会发现新的数组的每个单元映射到旧阵列中的一个2x2组单元。我想新阵列中的单元格的值是值的总和在旧阵列在该块中。
You'll notice that each cell of the new array maps to a 2x2 set of cells in the old array. I would like a cell's value in the new array to be the sum of the values in this block in the old array.
我能做到这一点如下:
import numpy
#Generate an example array
arr = numpy.random.randint(10,size=(4320,8640))
#Perform the transformation
arrtrans = numpy.array([ [ arr[y][x]+arr[y+1][x]+arr[y][x+1]+arr[y+1][x+1] for x in range(0,8640,2)] for y in range(0,4320,2)])
但是,这是缓慢的,不是一点点丑了。
But this is slow and more than a little ugly.
有没有办法做到这一点使用numpy的(或可互操作的封装)?
Is there a way to do this using Numpy (or an interoperable package)?
推荐答案
我不知道存在着需要的数据包,但是这code将计算速度更快。
I'm not sure there exists the package you want, but this code will compute much faster.
>>> arrtrans2 = arr[::2, ::2] + arr[::2, 1::2] + arr[1::2, ::2] + arr[1::2, 1::2]
>>> numpy.allclose(arrtrans, arrtrans2)
True
其中, :: 2
和 1 :: 2
按被翻译0,2 4,...
和 1,3,5,...
分别。
这篇关于总结numpy的阵列通过总结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!