1

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?

6
  • 2
    This smells like homework, What have you tried? Commented Sep 27, 2012 at 10:05
  • 2
    Where is that array function from? numpy? Commented Sep 27, 2012 at 10:06
  • Yes the array function is from numpy Commented Sep 27, 2012 at 10:08
  • I tried 1) a == b 2) a == b.any() Commented Sep 27, 2012 at 10:09
  • Wow, you tried so much. Perhaps consulting a tutorial might be helpful Commented Sep 27, 2012 at 10:11

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

On newer numpy versions the function is called np.in1d (or np.lib.arraysetops.in1d, but the best solution with arrays, at least if b is not small.
2

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.

5 Comments

This will be quite slow if a and b are large.
@BiRico All valid solutions, without knowing about numpy arrays, are that though :P
If b is large, I would probably opt for [x in set(b) for x in a] to avoid looping over b.
That will call set(b) len(a) times though. But yeah, obviously you could make changes to improve the performance.
Yes you are absolutely right, how about b = set(b); tuple(x in b for x in a), does that work?
2

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

Comments

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]

2 Comments

As other answers have shown this can be crushed down into a list or generator comprehension
I started typing my answer before there were any others. This answer may be unnecessarily verbose but it's still valid and could be of help to those who don't yet fully comprehend list comprehensions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.