Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why numpy returns true index while comparing integer and float value from two different list

How to avoid returning true index while comparing 10.5 and 10?

A = np.array([1,2,3,4,5,6,7,8,9,10.5])

B = np.array([1,7,10])

i = np.searchsorted(A,B)

print i   # [0 6 9]

I want to get the places of the exact matches: [0 6]

like image 691
Poka Avatar asked Feb 16 '26 05:02

Poka


1 Answers

You could use np.searchsorted with left and right and only keep those who don't return the same index for both:

>>> import numpy as np
>>> A = np.array([1,2,3,4,5,6,7,8,9,10.5])
>>> B = np.array([1,7,10])

>>> i = np.searchsorted(A, B, 'left')
>>> j = np.searchsorted(A, B, 'right')
>>> i[i!=j]
array([0, 6], dtype=int64)

That works because searchsorted returns the index where the element needs to be inserted if you want to keep the other array sorted. So when the value is present in the other array it returns the index before the match (left) and the index after the matches(right). So if the index differs there's an exact match and if the index is the same there's no exact match

like image 158
MSeifert Avatar answered Feb 17 '26 19:02

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!