Find nearest value in numpy array

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

    Here's a version that will handle a non-scalar "values" array:

    import numpy as np
    
    def find_nearest(array, values):
        indices = np.abs(np.subtract.outer(array, values)).argmin(0)
        return array[indices]
    

    Or a version that returns a numeric type (e.g. int, float) if the input is scalar:

    def find_nearest(array, values):
        values = np.atleast_1d(values)
        indices = np.abs(np.subtract.outer(array, values)).argmin(0)
        out = array[indices]
        return out if len(out) > 1 else out[0]
    

提交回复
热议问题