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?
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With