Numpy: find the index of elements in one array that occurs in another array

I have two 1D arrays and I want to find out if an element exists in one array in another array or not.

For instance:

import numpy as np
A = np.array([ 1, 48, 50, 78, 85, 97])
B = np.array([38, 43, 50, 62, 78, 85])

I want to:

C = [2,3,4] # since 50 in second array occurs in first array at index 2, 
            # similarly 78 in second array occurs in first array in index 3,
            # similarly for 85, it is index 4

I tried:

accuracy = np.searchsorted(A, B)

But it gives me unwanted results.

+4
source share
2 answers

You can use np.whereand np.in1d:

>>> np.where(np.in1d(A, B))[0]
array([2, 3, 4])

np.in1d(A, B)returns a boolean array indicating whether each value is found Ain B. np.wherereturns indexes of values True. (This will also work if your arrays are not sorted.)

+10
source

np.intersect1d, ( ) .

In [5]: np.intersect1d(A, B)
Out[5]: array([50, 78, 85])

, np.searchsorted :

In [7]: np.searchsorted(A, np.intersect1d(A, B))
Out[7]: array([2, 3, 4])
+3

All Articles