在没有循环的情况下查找二维数组中匹配行的索引(一次)
find indices of matching rows in 2d array without loop (one shot)
我想从二维数组 a 中找到多个匹配行
a = np.array([[2, 1],
[3, 3],
[4, 6],
[4, 8],
[4, 7],
[4, 3]])
我必须搜索以下条目
b = np.array([[4,6],
[4,7]])
我知道我可以遍历 b 并执行以下操作
for i in range(len(b)) :
print(np.where(np.all(a==b[i],axis=1))[0])
我得到关注
[2]
[4]
我可以不使用任何循环直接得到[[2],[4]]吗?
如果您想要索引,您通常会使用 arg_x
函数,例如 argmax
和 argwhere
。这里 np.argwhere
will give you the indices if you can figure out how to pass the correct list of booleans. You can do that with np.isin():
a = np.array([[2, 1],
[3, 3],
[4, 6],
[4, 8],
[4, 7],
[4, 3]])
b = np.array([[4,6], [4,7]])
np.argwhere(np.isin(a, b).all(axis=1))
哪个returns:
array([[2],
[4]])
这应该是一个快速的解决方案,注意到两对具有相同的第一个坐标:
np.where((a[:, 0] == 4) & ((a[:, 1] == 6) | (a[:, 1] == 7)))
# Out:
# (array([2, 4]),)
表达式
print((a[:, 0] == 4) & ((a[:, 1] == 6) | (a[:, 1] == 7)))
给予
[False False True False True False]
我想从二维数组 a 中找到多个匹配行
a = np.array([[2, 1],
[3, 3],
[4, 6],
[4, 8],
[4, 7],
[4, 3]])
我必须搜索以下条目
b = np.array([[4,6],
[4,7]])
我知道我可以遍历 b 并执行以下操作
for i in range(len(b)) :
print(np.where(np.all(a==b[i],axis=1))[0])
我得到关注
[2]
[4]
我可以不使用任何循环直接得到[[2],[4]]吗?
如果您想要索引,您通常会使用 arg_x
函数,例如 argmax
和 argwhere
。这里 np.argwhere
will give you the indices if you can figure out how to pass the correct list of booleans. You can do that with np.isin():
a = np.array([[2, 1],
[3, 3],
[4, 6],
[4, 8],
[4, 7],
[4, 3]])
b = np.array([[4,6], [4,7]])
np.argwhere(np.isin(a, b).all(axis=1))
哪个returns:
array([[2],
[4]])
这应该是一个快速的解决方案,注意到两对具有相同的第一个坐标:
np.where((a[:, 0] == 4) & ((a[:, 1] == 6) | (a[:, 1] == 7)))
# Out:
# (array([2, 4]),)
表达式
print((a[:, 0] == 4) & ((a[:, 1] == 6) | (a[:, 1] == 7)))
给予
[False False True False True False]