Is there a numpy-thonic way, e.g. function, to find the nearest value in an array?
Example:
np.find_nearest( array, value )
Is there a numpy-thonic way, e.g. function, to find the nearest value in an array?
Example:
np.find_nearest( array, value )
Here's an extension to find the nearest vector in an array of vectors.
Here is a version with scipy for @Ari Onasafari, answer "to find the nearest vector in an array of vectors"
Here's a version that will handle a non-scalar "values" array:
Or a version that returns a numeric type (e.g. int, float) if the input is scalar:
For large arrays, the (excellent) answer given by @Demitri is far faster than the answer currently marked as best. I've adapted his exact algorithm in the following two ways:
The function below works whether or not the input array is sorted.
The function below returns the index of the input array corresponding to the closest value, which is somewhat more general.
Note that the function below also handles a specific edge case that would lead to a bug in the original function written by @Demitri. Otherwise, my algorithm is identical to his.
This is a vectorized version of unutbu's answer:
IF your array is sorted and is very large, this is a much faster solution:
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.