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?
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)
np.in1d (or np.lib.arraysetops.in1d, but the best solution with arrays, at least if b is not small.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.
[x in set(b) for x in a] to avoid looping over b.set(b) len(a) times though. But yeah, obviously you could make changes to improve the performance.b = set(b); tuple(x in b for x in a), does that work?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).
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]
arrayfunction from? numpy?