Brendan
Brendan

Reputation: 19403

Equivalent of 'in' for comparing two Numpy arrays

In pure, unvectorised, Python I can use,

>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False

I would like to do something similar for arrays in Numpy i.e.

>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, False, False, True, False, True, False, False, False])

... although this does not work.

Is there a function or method that achieves this? If not what is the easiest way to do this?

Upvotes: 3

Views: 515

Answers (3)

krawyoti
krawyoti

Reputation: 20145

You are looking for in1d:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> np.in1d( a, b)
array([False, False, False, False,  True, False,  True, False, False, False], dtype=bool)

Upvotes: 8

Overmind Jiang
Overmind Jiang

Reputation: 633

You may want to implement some sort of string searching algorithms if you are going to test whether one sequence contains another sequence. Reference from Wikipedia

Upvotes: 0

moinudin
moinudin

Reputation: 138437

You're comparing two very different things. With the pure Python lists, you have an int and a list. With numpy, you have two numpy arrays. If you change a to an int, then it works as expected in numpy.

>>> a = 9
>>> b = np.array([5, 7, 12])
>>> a in b
False

Also note that what you show with two lists is quite an intuitive result. The returned array is showing you, for each value in array a, is it in b? 5 and 7 are, the others are not. Hence the given result.

Upvotes: 1

Related Questions