python - Numpy - 在另一个二维数组中查找二维数组的最有效方法

标签 python arrays numpy multidimensional-array

我是 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))

我尝试了像 isinwhere 这样的函数,但它们都搜索任何元素,而不是数组的整个形状。

这就是我的想法 - 迭代行和列,切片 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/

相关文章:

javascript - 获取嵌套数组中特定键的每个值的总金额

javascript - 如何从 div 数组中获取下一个对象?

python - 如何使用 numpy 使 for 循环更快

转置矩阵的 Python 32/64 位机器浮点求和不正确?

c - 你如何为c中的数组中的元素赋值?

Python:数组值以某种方式被改变

python - 类型错误:无法使用这些索引器对 <class 'pandas.indexes.base.Index' > 进行标签索引

python - 大型门户网站上的 web2py 或 grok(zope),

python - 当分母中的元素可能为零时,高效的逐元素矩阵除法

python - 使用 openCV for python 进行反投影