如何使用 NumPy 查找最接近给定值的数组索引
假设你有一个类似这样的一维数组
numpy_argmin_closest.py
arr = np.linspace(0, 10, 100)你想找到值最接近 8.5 的数组索引。
你可以通过首先计算与 8.5 的绝对差值来做到这一点:
numpy_abs_diff.py
np.abs(arr - 8.5)现在使用 np.argmin 查找值最小的数组索引(即 arr 的值最接近 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