"In" operator for numpy arrays?
<p>How can I do the "in" operation on a numpy array?
(Return True if an element is present in the given numpy array)</p>

<p>For strings, lists and dictionaries, the functionality is intuitive to understand.</p>

<p>Here's what I got when I applied that on a numpy array</p>

<pre><code>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
</code></pre>

<p>You could compare the input arrays for <code>equality</code>, which will perform <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasted</code></a> comparisons across all elements in <code>a</code> at each position in the last two axes against elements at corresponding positions in the second array. This will result in a boolean array of matches, in which we check for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="nofollow"><code>ALL</code></a> matches across the last two axes and finally check for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html" rel="nofollow"><code>ANY</code></a> match, like so -</p>

<pre><code>((a==b).all(axis=(1,2))).any()
</code></pre>

<p><strong>Sample run</strong></p>

<p>1) Inputs :</p>

<pre><code>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]])
</code></pre>

<p>2) Broadcasted elementwise comparisons :</p>

<pre><code>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)
</code></pre>

<p>3) <code>ALL</code> match across last two axes and finally <code>ANY</code> match :</p>

<pre><code>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
</code></pre>

<p>Following similar steps for <code>c</code> in <code>a</code> -</p>

<pre><code>In [73]: c
Out[73]: 
array([[300, 200,   0],
       [  0, 100, 100]])

In [74]: ((a==c).all(axis=(1,2))).any()
Out[74]: False
</code></pre>

python arrays numpy operators