+3 votes
in Programming Languages by (77.8k points)

I am using isin() function to find the indices of a set of elements in a Numpy array, but it returns an empty list, although those elements are present in the array.

Here is my sample code:

>>> import numpy as np

>>> a=np.array([11,12,13,14,15,16,17])

>>> b=set([13,17,11])

>>> np.isin(a,b)

array([False, False, False, False, False, False, False])

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

(array([], dtype=int64),)

What is missing/wrong in the code?

1 Answer

+1 vote
by (355k points)
selected by
 
Best answer

Variable 'b' needs to be a list or a Numpy array. Since you have declared it as a set, isin() is returning an empty list.

Make the following change in your code and it will work.

>>> import numpy as np
>>> a=np.array([11,12,13,14,15,16,17])
>>> b=set([13,17,11])
>>> np.isin(a,b)
array([False, False, False, False, False, False, False])
>>> np.isin(a,list(b)).nonzero()
(array([0, 2, 6]),)


...