Find nearest value in numpy array Find nearest value in numpy array numpy numpy

Find nearest value in numpy array


import numpy as npdef 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.5print(find_nearest(array, value))# 0.568743859261


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.


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()]