Find nearest value in numpy array

后端 未结 16 1607
被撕碎了的回忆
被撕碎了的回忆 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()]
    
    0 讨论(0)
  • 2020-11-22 10:46

    I think the most pythonic way would be:

     num = 65 # Input number
     array = n.random.random((10))*100 # Given array 
     nearest_idx = n.where(abs(array-num)==abs(array-num).min())[0] # If you want the index of the element of array (array) nearest to the the given number (num)
     nearest_val = array[abs(array-num)==abs(array-num).min()] # If you directly want the element of array (array) nearest to the given number (num)
    

    This is the basic code. You can use it as a function if you want

    0 讨论(0)
  • 2020-11-22 10:50
    import numpy as np
    def find_nearest(array, value):
        array = np.array(array)
        z=np.abs(array-value)
        y= np.where(z == z.min())
        m=np.array(y)
        x=m[0,0]
        y=m[1,0]
        near_value=array[x,y]
    
        return near_value
    
    array =np.array([[60,200,30],[3,30,50],[20,1,-50],[20,-500,11]])
    print(array)
    value = 0
    print(find_nearest(array, value))
    
    0 讨论(0)
  • 2020-11-22 10:51

    Here is a version with scipy for @Ari Onasafari, answer "to find the nearest vector in an array of vectors"

    In [1]: from scipy import spatial
    
    In [2]: import numpy as np
    
    In [3]: A = np.random.random((10,2))*100
    
    In [4]: A
    Out[4]:
    array([[ 68.83402637,  38.07632221],
           [ 76.84704074,  24.9395109 ],
           [ 16.26715795,  98.52763827],
           [ 70.99411985,  67.31740151],
           [ 71.72452181,  24.13516764],
           [ 17.22707611,  20.65425362],
           [ 43.85122458,  21.50624882],
           [ 76.71987125,  44.95031274],
           [ 63.77341073,  78.87417774],
           [  8.45828909,  30.18426696]])
    
    In [5]: pt = [6, 30]  # <-- the point to find
    
    In [6]: A[spatial.KDTree(A).query(pt)[1]] # <-- the nearest point 
    Out[6]: array([  8.45828909,  30.18426696])
    
    #how it works!
    In [7]: distance,index = spatial.KDTree(A).query(pt)
    
    In [8]: distance # <-- The distances to the nearest neighbors
    Out[8]: 2.4651855048258393
    
    In [9]: index # <-- The locations of the neighbors
    Out[9]: 9
    
    #then 
    In [10]: A[index]
    Out[10]: array([  8.45828909,  30.18426696])
    
    0 讨论(0)
  • 2020-11-22 10:52

    Here is a fast vectorized version of @Dimitri's solution if you have many values to search for (values can be multi-dimensional array):

    #`values` should be sorted
    def get_closest(array, values):
        #make sure array is a numpy array
        array = np.array(array)
    
        # get insert positions
        idxs = np.searchsorted(array, values, side="left")
    
        # find indexes where previous index is closer
        prev_idx_is_less = ((idxs == len(array))|(np.fabs(values - array[np.maximum(idxs-1, 0)]) < np.fabs(values - array[np.minimum(idxs, len(array)-1)])))
        idxs[prev_idx_is_less] -= 1
    
        return array[idxs]
    

    Benchmarks

    > 100 times faster than using a for loop with @Demitri's solution`

    >>> %timeit ar=get_closest(np.linspace(1, 1000, 100), np.random.randint(0, 1050, (1000, 1000)))
    139 ms ± 4.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    >>> %timeit ar=[find_nearest(np.linspace(1, 1000, 100), value) for value in np.random.randint(0, 1050, 1000*1000)]
    took 21.4 seconds
    
    0 讨论(0)
  • 2020-11-22 10:58

    If you don't want to use numpy this will do it:

    def find_nearest(array, value):
        n = [abs(i-value) for i in array]
        idx = n.index(min(n))
        return array[idx]
    
    0 讨论(0)
提交回复
热议问题