Find nearest value in numpy array

后端 未结 16 2007
被撕碎了的回忆
被撕碎了的回忆 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: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

提交回复
热议问题