user996018
user996018

Reputation: 71

checking if the elements of an array are present in another array in python

I have two arrays

a = array([1,2,3])    
b = array([2,7])

Now I want to check if elements of a are in b and the returning answer should be (False, True, False). Is there some simple way to do this without using functions?

Upvotes: 1

Views: 4318

Answers (4)

Bi Rico
Bi Rico

Reputation: 25813

How about this:

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

update, thanks seberg. With newer verions of numpy this is:

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

Upvotes: 3

Pierre GM
Pierre GM

Reputation: 20339

Using only numpy:

>>> (a[:,None] == b).any(axis=-1)

(So, we transform a from a (N,) to a (N,1) array, then test for equality using numpy's broadcasting. We end up with a (N, M) array (assuming that b had a shape (M,)...), and we just check whether ther's a True on each row with any(axis=-1).

Upvotes: 2

Hubro
Hubro

Reputation: 59333

Well, this is how I'd do it with lists:

>>> a = [1, 2, 3]
>>> b = [2, 7]
>>> result = []
>>>
>>> for x in a:
...    result.append(x in b)
...
>>> print result
[False, True, False]

Upvotes: 1

poke
poke

Reputation: 387667

With standard python lists:

>>> a = [1, 2, 3]
>>> b = [2, 7]
>>> tuple(x in b for x in a)
(False, True, False)

Assuming that your array function returns an object that also supports both iterations and the in operator, it should work the same.

Upvotes: 2

Related Questions