Find nearest value in numpy array?

Find nearest value in numpy array?

Asked on November 10, 2018 in Python.
Add Comment


  • 3 Answer(s)

      Use this code to find nearest value in numpy array:

    import numpy as np
    def find_nearest(array, value):
        array = np.asarray(array)
        idx = (np.abs(array - value)).argmin()
        return array[idx]
    array = np.random.random(10)
    print(array)
    # [ 0.21069679 0.61290182 0.63425412 0.84635244 0.91599191 0.00213826
    #     0.17104965 0.56874386 0.57319379 0.28719469]
    value = 0.5
    print(find_nearest(array, value))
    # 0.568743859261
    
    Answered on November 10, 2018.
    Add Comment

       Try this extension to find the nearest vector in an array of vectors:

    import numpy as np
    def find_nearest_vector(array, value):
        idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
        return array[idx]
    A = np.random.random((10,2))*100
    """ A = array([[ 34.19762933, 43.14534123],
        [ 48.79558706, 47.79243283],
        [ 38.42774411, 84.87155478],
        [ 63.64371943, 50.7722317 ],
        [ 73.56362857, 27.87895698],
        [ 96.67790593, 77.76150486],
        [ 68.86202147, 21.38735169],
        [ 5.21796467, 59.17051276],
        [ 82.92389467, 99.90387851],
        [ 6.76626539, 30.50661753]])"""
    pt = [6, 30]
    print find_nearest_vector(A,pt)
    # array([ 6.76626539, 30.50661753])
    
    Answered on November 10, 2018.
    Add Comment

      If there is no interest in use numpy,try this:

    def find_nearest(array, value):
        n = [abs(i-value) for i in array]
        idx = n.index(min(n))
        return array[idx]
    
    Answered on November 10, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.