我是 numpy 新手,试图了解如何在另一个二维数组中搜索二维数组。我不需要索引,只需要 True/False
例如,我有一个形状为 10x10 的数组,全部为 1,并且在某处有 2x2 个零:
ar = np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 0, 1, 1, 0, 1],
[1, 1, 0, 1, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 0, 1, 1, 1, 2],
[1, 1, 0, 1, 1, 0, 1, 1, 1, 1]]
)
我想找到另一个数组
ar2 = np.zeros((2,2))
我尝试了像 isin
和 where
这样的函数,但它们都搜索任何元素,而不是数组的整个形状。
这就是我的想法 - 迭代行和列,切片 2x2 数组并将其与零数组进行比较:
for r, c in np.ndindex(ar.shape):
if r-1>=0 and c-1>=0 and np.array_equal(ar[r - 1:r + 1, c - 1:c + 1], ar2):
print(f'found it {r}:{c}')
我不确定这是否是最好的解决方案,但至少它有效。也许有一些更简单、更快的方法来搜索 2x2 零?
最佳答案
我认为使用 scikit image
library可能是最好的方法之一:
from skimage.util import view_as_windows
view_ = view_as_windows(ar, (2, 2))
res_temp = np.all((view_ == ar2[None, ...]), (-2, -1))
result = np.nonzero(res_temp)
# (array([4], dtype=int64), array([4], dtype=int64))
这将获得索引。为了获得与代码相同的结果,索引必须加一。
关于python - Numpy - 在另一个二维数组中查找二维数组的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73522465/