繁体   English   中英

相同形状数组的掩码

[英]Mask for an array in the same shape

Array2[:,0] 包含 array1 行索引,array2[:,1] 包含 array1 元素值。 我想以矢量化的方式获得与 array1 相同形状的掩码。

array1=
[[0 1 2]
 [3 4 5]
 [6 7 8]]

array2=
[[0 1]
 [1 3]
 [1 5]
 [2 7]
 [2 9]]

代码:

array1 = np.arange(9).reshape(-1,3)
array2 = np.arange(10).reshape(-1,2)
array2[:,0]=[0,1,1,2,2]

print(array1[array2[:, 0]] == array2[:, 1,None])

我得到的结果:

[[False  True False]
 [ True False False]
 [False False  True]
 [False  True False]
 [False False False]]

我想得到的结果:

[[False  True False]
 [ True False  True]
 [False  True False]

编辑:循环解决方案如下所示:

mask=np.zeros_like(array1)
for (y,x) in array2:
    mask[y,(np.where(array1[y,:] == x))] = True

您可以执行回映射:

array1 = np.arange(9).reshape(-1,3)
array2 = np.arange(10).reshape(-1,2)
array2[:,0] = [0,1,1,2,2]

xs, ys = np.where(array1[array2[:, 0]] == array2[:, 1,None])

mask = np.zeros_like(array1, dtype=bool)
mask[array2[xs,0], ys] = True

这为我们提供了给定的样本数据:

>>> mask
array([[False,  True, False],
       [ True, False,  True],
       [False,  True, False]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM