Python: intersection indices numpy array

Viewed 39763

How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with intersect1d:

import numpy as np

a = np.array(xrange(11))
b = np.array([2, 7, 10])
inter = np.intersect1d(a, b)
# inter == array([ 2,  7, 10])

But how can I get the indices into a of the values in inter?

4 Answers
indices = np.argwhere(np.in1d(a,b))

For Python >= 3.5, there's another solution to do so

Other Solution

Let we go through this step by step.

Based on the original code from the question

import numpy as np

a = np.array(range(11))
b = np.array([2, 7, 10])
inter = np.intersect1d(a, b)

First, we create a numpy array with zeros

c = np.zeros(len(a))
print (c)

output

>>> [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]

Second, change array value of c using intersect index. Hence, we have

c[inter] = 1
print (c)

output

>>>[ 0.  0.  1.  0.  0.  0.  0.  1.  0.  0.  1.]

The last step, use the characteristic of np.nonzero(), it will return exactly the index of the non-zero term you want.

inter_with_idx = np.nonzero(c)
print (inter_with_idx)

Final output

array([ 2, 7, 10])

Reference

[1] numpy.nonzero

Related