Find numpy vectors in a set quickly
<p>I have a numpy array, for example:</p>

<pre><code>a = np.array([[1,2],
              [3,4],
              [6,4],
              [5,3],
              [3,5]])
</code></pre>

<p>and I also have a set</p>

<pre><code>b = set((1,2),(6,4),(9,9))
</code></pre>

<p>I want to find the index of vectors that exist in set b, here is</p>

<pre><code>[0, 2]
</code></pre>

<p>but I use a for loop to implement this, is there a convinient way to do this job avoiding for loop?
The for loop method I used:</p>

<pre><code>record = []
for i in range(a.shape[0]):
    if (a[i, 0], a[i, 1]) in b:
        record.append(i)
</code></pre>

<p>First off, convert the set to a NumPy array -</p>

<pre><code>b_arr = np.array(list(b))
</code></pre>

<p>Then, based on <a href="http://stackoverflow.com/a/38674038/3293881"><code>this post</code></a>, you would have three approaches. Let's use the second approach for efficiency -</p>

<pre><code>dims = np.maximum(a.max(0),b_arr.max(0)) + 1
a1D = np.ravel_multi_index(a.T,dims)
b1D = np.ravel_multi_index(b_arr.T,dims)    
out = np.flatnonzero(np.in1d(a1D,b1D))
</code></pre>

<p>Sample run -</p>

<pre><code>In [89]: a
Out[89]: 
array([[1, 2],
       [3, 4],
       [6, 4],
       [5, 3],
       [3, 5]])

In [90]: b
Out[90]: {(1, 2), (6, 4), (9, 9)}

In [91]: b_arr = np.array(list(b))

In [92]: dims = np.maximum(a.max(0),b_arr.max(0)) + 1
    ...: a1D = np.ravel_multi_index(a.T,dims)
    ...: b1D = np.ravel_multi_index(b_arr.T,dims)    
    ...: out = np.flatnonzero(np.in1d(a1D,b1D))
    ...: 

In [93]: out
Out[93]: array([0, 2])
</code></pre>

python numpy set vectorization lookup