views:

406

answers:

2

Hi, is there a numpy-thonic way, e.g. function, to find the 'nearest value' in an array? example:

np.find_nearest( array, value )

thanks in advance!

A: 

It helps if we first understand some more backround:

  • Nearest to what? The value?
  • Is the data ordered in some way?

Personally I'd start with a method to calculate deviation from your current value. I'd then (depending on how the data is currently sorted) work out how most efficiently to search it to find the minimum distance.

Jon Cage
+8  A: 
import numpy as np
def find_nearest(array,value):
    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
unutbu
+1: Tidy answer :-)
Jon Cage
I would suggest the more direct `return np.abs(array-value).min()`. In fact, there is no need for any index, when the nearest *element* is what is looked for.
EOL
@EOL: `return np.abs(array-value).min()` gives the wrong answer. This gives you the min of the absolute value distance, and somehow we need to return the actual array value. We could add `value` and come close, but the absolute value throws a wrench into things...
unutbu
@~unutbu You're right, my bad. I can't think of anything better than your solution!
EOL