Find nearest value in numpy array

后端 未结 16 1876
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 10:18

Is there a numpy-thonic way, e.g. function, to find the nearest value in an array?

Example:

np.find_nearest( array, value )
16条回答
  •  [愿得一人]
    2020-11-22 10:41

    For 2d array, to determine the i, j position of nearest element:

    import numpy as np
    def find_nearest(a, a0):
        idx = (np.abs(a - a0)).argmin()
        w = a.shape[1]
        i = idx // w
        j = idx - i * w
        return a[i,j], i, j
    

提交回复
热议问题