Find nearest value in numpy array

后端 未结 16 1880
被撕碎了的回忆
被撕碎了的回忆 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:45

    With slight modification, the answer above works with arrays of arbitrary dimension (1d, 2d, 3d, ...):

    def find_nearest(a, a0):
        "Element in nd array `a` closest to the scalar value `a0`"
        idx = np.abs(a - a0).argmin()
        return a.flat[idx]
    

    Or, written as a single line:

    a.flat[np.abs(a - a0).argmin()]
    

提交回复
热议问题