Equivalent to in to compare two Numpy arrays

In clean, unclaimed 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 ie

>>> 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 achieve this? If this is not the easiest way to do this?

+3
source share
3 answers

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)
+8
source

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

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

, , , . , a, b? 5 7, . , .

+1

You might want to implement some string search algorithms if you are going to check if one sequence contains another sequence. Wikipedia link

0
source

Source: https://habr.com/ru/post/1777657/


All Articles