I have an array of my_values for which I am trying infer the closest, smaller value in an array of true_values. Using the find_nearest function below doesn't accomplish what I want it to. How can I append this to find the nearest, smaller value?
import numpy as np
true_values = np.array([4.5, 3.0, 2.4, 1.2, 0.1])
my_values = np.array([0.8, 2.1, 3.01, 8.0, 0.2, 2.6, 2.1, 3.99, 1.3])
def find_nearest(array,value):
idx = np.abs((array-value)).argmin()
return array[idx]
nearest = []
for i in my_values:
nearest.append(find_nearest(true_values,i))
print nearest
# [1.2, 2.4, 3.0, 4.5, 0.1, 2.4, 2.4, 4.5, 1.2]
But instead I would like the output to be
nearest = [0.1, 1.2, 3.0, 4.5, 0.1, 2.4, 1.2, 3.0, 1.2]
The first answer here: How to find nearest value that is greater in numpy array? accomplishes this for the nearest, larger value. Perhaps this can be changed to find the nearest, smaller value?
true_valuesalways sorted? If so, you might want to look into thesearchsortedfunction.array-valueis negative.