The Python Oracle

Numpy: How to check if array contains certain numbers?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC I Beethoven Sonata No 31 in A Flat M

--

Chapters
00:00 Question
00:37 Accepted answer (Score 10)
01:39 Answer 2 (Score 14)
02:16 Answer 3 (Score 5)
02:39 Answer 4 (Score -1)
02:52 Thank you

--

Full question
https://stackoverflow.com/questions/1056...

Accepted answer links:
[numpy.setdiff1d(ar1, ar2)]: http://docs.scipy.org/doc/numpy/referenc...

Answer 3 links:
[in1d]: http://docs.scipy.org/doc/numpy/referenc...
[np.isin]: https://numpy.org/doc/stable/reference/g...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy

#avk47



ANSWER 1

Score 14


You could alway use a set:

>>> a = numpy.array([123, 412, 444])
>>> b = numpy.array([123, 321])
>>> set(b) in set(a)
False

Or with newer versions of numpy:

>>> numpy.in1d(b,a)
array([ True, False], dtype=bool)

If you want just 'the answer' rather than an array:

>>> numpy.in1d(b,a).all()
False

Or (least desirable):

>>> numpy.array([x in a for x in b]) 
array([ True, False], dtype=bool)

Looping is slowish on numpy arrays and should be avoided.




ACCEPTED ANSWER

Score 11


You can use set difference to determine what you are looking for. Numpy has a built-in function called numpy.setdiff1d(ar1, ar2):

Return the sorted, unique values in ar1 that are not in ar2.

Example for your case:

>>> a = np.array([123, 412, 444])
>>> b = np.array([123, 321])
>>> diff = np.setdiff1d(b, a)
>>> print diff
array([321])
>>> if diff.size:
>>>    print "Not passed"

So for your case, you would do a set difference you would subtract a from b and obtain an array with elements in b which are not in a. Then you can check if that was empty or not. As you can see, the output is 312, which is an entry present in a but not in b; the length of it is now larger then zero, therefore there were elements in b which were not present in a.




ANSWER 3

Score 5


that means you want to check if each element of b is contained in a. in1d does that:

from numpy import array, in1d
a = array([123, 412, 444])
b = array([123, 321])
print in1d(b, a).all()

Update from 2021: nowadays np.isin is recommended