Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find nearest value in numpy array

Is there a numpy-thonic way, e.g. function, to find the nearest value in an array?

Example:

np.find_nearest( array, value ) 
like image 755
Fookatchu Avatar asked Apr 02 '10 11:04

Fookatchu


1 Answers

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 
like image 133
unutbu Avatar answered Sep 21 '22 09:09

unutbu