如何从两个数组中找到匹配的元素和索引?

이원석*_*이원석 4 python idl intersection match indices

例如,

a = [1, 1, 2, 4, 4, 4, 5, 6, 7, 100]
b = [1, 2, 2, 2, 2, 4, 5, 7, 8, 100]
Run Code Online (Sandbox Code Playgroud)

我可以使用以下方法找到匹配的元素:

np.intersect1d(a,b)
Run Code Online (Sandbox Code Playgroud)

输出:

array([  1,   2,   4,   5,   7, 100])
Run Code Online (Sandbox Code Playgroud)

a那么,如何分别获取数组和中匹配元素的索引b

IDL 中有一个函数"match"- https://www.l3harrisgeospatial.com/docs/match.html

Python中有类似的函数吗?

Chr*_*ris 5

用于:return_indicesnumpy.intersect1d

intersect, ind_a, ind_b = np.intersect1d(a,b, return_indices=True)
Run Code Online (Sandbox Code Playgroud)

输出:

intersect
# array([  1,   2,   4,   5,   7, 100])
ind_a
# array([0, 2, 3, 6, 8, 9], dtype=int64)
ind_b
# array([0, 1, 5, 6, 7, 9], dtype=int64)
Run Code Online (Sandbox Code Playgroud)

然后可以重复使用,例如:

np.array(a)[ind_a]
np.array(b)[ind_b]

array([  1,   2,   4,   5,   7, 100])
Run Code Online (Sandbox Code Playgroud)

  • 有时我们只是忽略了为我们提供所需一切的文档:) (2认同)