Python 累积加法(单位:numpy)

Python 累积加法(单位:numpy),python,numpy,Python,Numpy,如何使循环更快 import numpy as np # naively small input data image = np.array( [[2,2],[2,2]] ) polarImage = np.array( [[0,0],[0,0]] ) a = np.array( [[0,0],[0,1]] ) r = np.array( [[0,0],[0,1]] ) # TODO - this loop is too slow it = np.nditer(image, flags=['

如何使循环更快

import numpy as np

# naively small input data
image = np.array( [[2,2],[2,2]] )
polarImage = np.array( [[0,0],[0,0]] )
a = np.array( [[0,0],[0,1]] )
r = np.array( [[0,0],[0,1]] )

# TODO - this loop is too slow
it = np.nditer(image, flags=['multi_index'])
while not it.finished:
  polarImage[ a[it.multi_index],r[it.multi_index] ] += it[0]
  it.iternext()

print polarImage

# this is fast but doesn't cumulate the results!
polarImage = np.array( [[0,0],[0,0]] )
polarImage[a,r]+= image

print polarImage
第一次打印返回:

[[6 0]
 [0 2]]
第二点:

[[2 0]
 [0 2]]

通过累积加法,我的意思是,有时必须将来自图像的两个或多个值加到一个极化的单元格中。在这种情况下,使用
nditer
会模糊该过程,而不会提高速度。我们更习惯于看到双循环:

In [670]: polarImage=np.zeros_like(image)
In [671]: for i in range(2):
    for j in range(2):
        polarImage[a[i,j],r[i,j]] += image[i,j]

In [672]: polarImage
Out[672]: 
array([[6, 0],
       [0, 2]])
polarImage[a,r]+=image
由于缓冲问题而无法工作。
(0,0)
索引对使用了3次。有一种专门针对这种情况的
ufunc
方法,
at
。它执行无缓冲操作;很可能使用与第一个示例相同的
nditer
,但使用的是编译后的代码

In [676]: polarImage=np.zeros_like(image)
In [677]: np.add.at(polarImage, (a,r), image)
In [678]: polarImage
Out[678]: 
array([[6, 0],
       [0, 2]])

请给出输入示例,将其转化为一个示例?我不清楚你的目标是什么。请再看一遍。np.add.at就是我要找的。速度快了10倍!