Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find matching elements and indices from two arrays?

For example,

a = [1, 1, 2, 4, 4, 4, 5, 6, 7, 100]
b = [1, 2, 2, 2, 2, 4, 5, 7, 8, 100]

I can find the matching elements using:

np.intersect1d(a,b)

Output:

array([  1,   2,   4,   5,   7, 100])

Then, how can I get the indices of matched elements in arrays a and b, respectively ?

There is a function in IDL as "match" - https://www.l3harrisgeospatial.com/docs/match.html

Is there a similar function in Python?

like image 245
이원석 Avatar asked Mar 01 '23 19:03

이원석


1 Answers

Use return_indices in numpy.intersect1d:

intersect, ind_a, ind_b = np.intersect1d(a,b, return_indices=True)

Output:

intersect
# array([  1,   2,   4,   5,   7, 100])
ind_a
# array([0, 2, 3, 6, 8, 9], dtype=int64)
ind_b
# array([0, 1, 5, 6, 7, 9], dtype=int64)

Which can then be reused like:

np.array(a)[ind_a]
np.array(b)[ind_b]

array([  1,   2,   4,   5,   7, 100])
like image 55
Chris Avatar answered Mar 16 '23 02:03

Chris