且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在另一个数组中查找一个数组的匹配索引

更新时间:2022-06-22 22:29:08

您可以使用 np.in1d -

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])