+1 vote
in Programming Languages by (88.8k points)

I am using Numpy isin() function to find the indices of all elements of an array in another array. However, it seems slower for bigger arrays. Is there any faster alternatives for this function?

Here is a simple example:

a= np.array([12,34,5,2,15,112,345,232), 

b=[2,5] 

np.isin(a,b).nonzero()

1 Answer

+2 votes
by (15.9k points)
selected by
 
Best answer

Since your arrays are 1D, you can use np.in1d() function, which is sometimes faster than np.isin().

Here is an example:

>>> a= np.array([12,34,5,2,15,112,345,232])

>>> b=[2,5]

>>> np.in1d(a,b).nonzero()

(array([2, 3]),)

Another approach is to convert the array whose elements you want to search in another array to a set. The set lookup is O(1).  

Here is an example:

>>> np.nonzero([x in set(b) for x in a])

(array([2, 3]),)


...