The "In" operator for numpy arrays?

How can I do the in operation in a numpy array? (Return True if the element is present in the given numpy array)

For strings, lists, and dictionaries, the functionality is intuitive.

Here is what I got when I applied this in a numpy array

a
array([[[2, 3, 0],
    [1, 0, 1]],

   [[3, 2, 0],
    [0, 1, 1]],

   [[2, 2, 0],
    [1, 1, 1]],

   [[1, 3, 0],
    [2, 0, 1]],

   [[3, 1, 0],
    [0, 2, 1]]])

b = [[3, 2, 0],
    [0, 1, 1]]

b in a
True
#Aligned with the expectation

c = [[300, 200, 0],
    [0, 100, 100]]

c in a
True
#Not quite what I expected
+5
source share
2 answers

equality, , broadcasted . a , ALL , , ANY , :

((a==b).all(axis=(1,2))).any()

1) :

In [68]: a
Out[68]: 
array([[[2, 3, 0],
        [1, 0, 1]],

       [[3, 2, 0],
        [0, 1, 1]],

       [[2, 2, 0],
        [1, 1, 1]],

       [[1, 3, 0],
        [2, 0, 1]],

       [[3, 1, 0],
        [0, 2, 1]]])

In [69]: b
Out[69]: 
array([[3, 2, 0],
       [0, 1, 1]])

2) :

In [70]: a==b
Out[70]: 
array([[[False, False,  True],
        [False, False,  True]],

       [[ True,  True,  True],
        [ True,  True,  True]],

       [[False,  True,  True],
        [False,  True,  True]],

       [[False, False,  True],
        [False, False,  True]],

       [[ True, False,  True],
        [ True, False,  True]]], dtype=bool)

3) ALL , , ANY :

In [71]: (a==b).all(axis=(1,2))
Out[71]: array([False,  True, False, False, False], dtype=bool)

In [72]: ((a==b).all(axis=(1,2))).any()
Out[72]: True

c - a

In [73]: c
Out[73]: 
array([[300, 200,   0],
       [  0, 100, 100]])

In [74]: ((a==c).all(axis=(1,2))).any()
Out[74]: False
+5

, , , , , , .

Numpy 1.13 2017 , isin(), :

import numpy as np

a = np.array([[[2, 3, 0],
               [1, 0, 1]],
              [[3, 2, 0],
               [0, 1, 1]],
              [[2, 2, 0],
               [1, 1, 1]],
              [[1, 3, 0],
               [2, 0, 1]],
              [[3, 1, 0],
               [0, 2, 1]]])

b = [[3, 2, 0],
     [0, 1, 1]]

print np.isin(b,a)

# [[ True  True  True]
#  [ True  True  True]]

c = [[300, 200, 0],
    [0, 100, 100]]

print np.isin(c,a)

# [[False False  True]
#  [ True False False]]

, np.all() , .

0

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


All Articles