I found this post: Python: finding an element in an array
and it’s about returning the index of an array through matching the values.
On the other hand, what I am thinking of doing is similar but different. I would like to find the nearest value for the target value. For example I am looking for 4.2 but I know in the array there is no 4.2 but I want to return the index of the value 4.1 instead of 4.4.
What would be the fastest way of doing it?
I am thinking of doing it the old way like how I used to do it with Matlab, which is using the array A where I want to get the index from to minus the target value and take the absolute of it, then select the min. Something like this:-
[~,idx] = min(abs(A - target))
That is Matlab code but I am newbie in Python so I am thinking, is there a fast way of doing it in Python?
Thank you so much for your help!
This is similar to using bisect_left, but it’ll allow you to pass in an array of targets
Some explanation:
First the general case:
idx = A.searchsorted(target)returns an index for eachtargetsuch thattargetis betweenA[index - 1]andA[index]. I call theseleftandrightso we know thatleft < target <= right.target - left < right - targetisTrue(or 1) when target is closer toleftandFalse(or 0) when target is closer toright.Now the special case: when
targetis less than all the elements ofA,idx = 0.idx = np.clip(idx, 1, len(A)-1)replaces all values ofidx< 1 with 1, soidx=1. In this caseleft = A[0],right = A[1]and we know thattarget <= left <= right. Therefor we know thattarget - left <= 0andright - target >= 0sotarget - left < right - targetisTrueunlesstarget == left == rightandidx - True = 0.There is another special case if
targetis greater than all the elements ofA, In that caseidx = A.searchsorted(target)andnp.clip(idx, 1, len(A)-1)
replaceslen(A)withlen(A) - 1soidx=len(A) -1andtarget - left < right - targetends upFalseso idx returnslen(A) -1. I’ll let you work though the logic on your own.For example: