在另一个数组中查找一个数组的匹配项的索引 [英] Finding indices of matches of one array in another array
问题描述
我有两个 numpy 数组,A 和 B.A 包含唯一值,B 是 A 的子数组.现在我正在寻找一种方法来获取 A 中 B 值的索引.
I have two numpy arrays, A and B. A conatains unique values and B is a sub-array of A. Now I am looking for a way to get the index of B's values within A.
例如:
A = np.array([1,2,3,4,5,6,7,8,9,10])
B = np.array([1,7,10])
# I need a function fun() that:
fun(A,B)
>> 0,6,9
推荐答案
您可以使用 np.in1d
与 np.nonzero
-
You can use np.in1d
with np.nonzero
-
np.nonzero(np.in1d(A,B))[0]
您也可以使用 np.searchsorted代码>
,如果你关心维护顺序-
You can also use np.searchsorted
, if you care about maintaining the order -
np.searchsorted(A,B)
对于一般情况,当 A
&B
是未排序的数组,你可以在 np.searchsorted
中引入 sorter
选项,就像这样 -
For a generic case, when A
& B
are unsorted arrays, you can bring in the sorter
option in np.searchsorted
, like so -
sort_idx = A.argsort()
out = sort_idx[np.searchsorted(A,B,sorter = sort_idx)]
我会添加我最喜欢的 broadcasting
也用于解决一般情况 -
I would add in my favorite broadcasting
too in the mix to solve a generic case -
np.nonzero(B[:,None] == A)[1]
样品运行 -
In [125]: A
Out[125]: array([ 7, 5, 1, 6, 10, 9, 8])
In [126]: B
Out[126]: array([ 1, 10, 7])
In [127]: sort_idx = A.argsort()
In [128]: sort_idx[np.searchsorted(A,B,sorter = sort_idx)]
Out[128]: array([2, 4, 0])
In [129]: np.nonzero(B[:,None] == A)[1]
Out[129]: array([2, 4, 0])
这篇关于在另一个数组中查找一个数组的匹配项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!