How to find array index closest to a given value using NumPy
Let’s say you have an 1D array like
numpy_argmin_closest.py
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:
numpy_abs_diff.py
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)
numpy_argmin_example.py
np.argmin(np.abs(arr - 8.5))Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow