luffe luffe - 2 years ago 320
Python Question

Numpy: How to check if array contains certain numbers?

For example: I have

a = np.array([123, 412, 444])

b = np.array([123, 321])

I want to know if
contains all the elements in
. Is there a simple operation for this? In this case that would not be true.

Answer Source

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
>>> 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download