首页 > 解决方案 > 迭代两个具有索引的 2D numpy 数组

问题描述

我有两个相同形状的 2D numpy 数组。有没有办法同时遍历它们,同时从两个表和它们的索引中获取一对元素?

例如,我有两个数组

before = np.array(
    [[0, 0, 0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0, 0, 0]],
    dtype=int
)
after = np.array(
    [[0, 0, 1, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 1, 0, 0, 1]],
    dtype=int
)

我想zerobefore表中获取已转换为表中one的每个表的索引列表after- 在这种情况下将是[(0, 2), (1, 4), (1, 7)]

numpy.ndenumerate非常接近我想要实现的目标,但它一次只能遍历一个数组。

标签: pythonarraysnumpy

解决方案


您可以将这两个条件传递给np.logical_and,然后用于np.argwhere查找同时满足这两个条件的索引:

idx = np.argwhere(np.logical_and(before==0, after==1))

输出:

[[0 2]
 [1 4]
 [1 7]]

推荐阅读