How to find array index closest to a given value using NumPy
Let’s say you have an 1D array like
arr = np.linspace(0, 10, 100)
and you wanted to find the array index where the value is closest to 8.5
.
You can do this by first computing the absolute difference to 8.5
:
np.abs(arr - 8.5)
and now using np.argmin
to find the array index where the value is minimal (i.e. the index where the value of arr
is closest to 8.5
)
np.argmin(np.abs(arr - 8.5))