Say I have:
[1, 2, 3, 4]
and the integer
6
I want to compare 6
with every element in the list and return the element with the smallest absolute value difference which in this case is 4
. Is there an efficient Numpy
way to do it?
You can use argmin
on the absolute difference to extract the index, which can then be used to extract the element:
a = np.array([1, 2, 3, 4])
a[np.abs(a - 6).argmin()]
# 4
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