如何用掩码和索引替换双 for 循环?

How to replace a double for-loop with mask and indexing?

我有几个嵌套的 for 循环可以做正确的事情(数组的掩码副本)。然而性能太慢了,我觉得必须有更好的 Pythonic 方式来做到这一点。目标是使用掩码确定何时从源复制数据,使用坐标作为源的索引。有效的循环代码如下:

import numpy as np
dest = np.zeros((4,4,2))
source = range(32)
source = np.reshape(source,(4,4,2))
mask = np.ones((4,4),bool)
mask[1,0] = 0
coord = np.ones((4,4,2),int)

for y in range (0,dest.shape[0]):
    for x in range (0, dest.shape[1]):
        if np.all(mask[y,x]):
            dest[y,x] = source[coord[y,x,0], coord[y,x,1]]

print dest

在 运行 之后,dest 看起来像这样:

[[[ 10.  11.]
  [ 10.  11.]
  [ 10.  11.]
  [ 10.  11.]]
 [[  0.   0.]
  [ 10.  11.]
  [ 10.  11.]
  [ 10.  11.]]
 [[ 10.  11.]
  [ 10.  11.]
  [ 10.  11.]
  [ 10.  11.]]
 [[ 10.  11.]
  [ 10.  11.]
  [ 10.  11.]
  [ 10.  11.]]]

source[1,1] 被复制到所有 dest,除了 dest[1,0],因为 mask[1,0] 被设置为 Falsemask 的其余部分是 True。谁能告诉我如何用更高效的东西替换循环?

使用numpy.where. You have to add an extra dimension to mask so it will broadcast.

dest = np.where(mask[:,:,None], source[coord[:,:,0], coord[:,:,1]], dest)

或者如果合适的话:

dest = np.where(mask[:,:,None], source[coord[:,:,0], coord[:,:,1]], np.zeros((4,4,2)))