Find nearest value in numpy array

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

    This is a vectorized version of unutbu's answer:

    def find_nearest(array, values):
        array = np.asarray(array)
    
        # the last dim must be 1 to broadcast in (array - values) below.
        values = np.expand_dims(values, axis=-1) 
    
        indices = np.abs(array - values).argmin(axis=-1)
    
        return array[indices]
    
    
    image = plt.imread('example_3_band_image.jpg')
    
    print(image.shape) # should be (nrows, ncols, 3)
    
    quantiles = np.linspace(0, 255, num=2 ** 2, dtype=np.uint8)
    
    quantiled_image = find_nearest(quantiles, image)
    
    print(quantiled_image.shape) # should be (nrows, ncols, 3)
    
    0 讨论(0)
  • 2020-11-22 11:01

    Maybe helpful for ndarrays:

    def find_nearest(X, value):
        return X[np.unravel_index(np.argmin(np.abs(X - value)), X.shape)]
    
    0 讨论(0)
  • 2020-11-22 11:04

    IF your array is sorted and is very large, this is a much faster solution:

    def find_nearest(array,value):
        idx = np.searchsorted(array, value, side="left")
        if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
            return array[idx-1]
        else:
            return array[idx]
    

    This scales to very large arrays. You can easily modify the above to sort in the method if you can't assume that the array is already sorted. It’s overkill for small arrays, but once they get large this is much faster.

    0 讨论(0)
提交回复
热议问题