The given value is 6.6. But the value 6.6 is not in the array (data below). But the nearest value to the given value is 6.7. How can I get this position?
import numpy as np
data = np.array([[2.0, 3.0, 6.5, 6.5, 12.0],[1,2,3,4,5]],dtype=float)
The given value is 6.6. But the value 6.6 is not in the array (data below). But the nearest value to the given value is 6.7. How can I get this position?
import numpy as np
data = np.array([[2.0, 3.0, 6.5, 6.5, 12.0],[1,2,3,4,5]],dtype=float)
You can get like this:
data[(np.fabs(data-6.6)).argmin(axis=0)]
output:
6.7
EDIT: for 2d:
If it is python 2.x:
map(lambda x:x[(np.fabs(x-6.6)).argmin(axis=0)], data)
python 3.x:
[r for r in map(lambda x:x[(np.fabs(x-6.6)).argmin(axis=0)], data)]
results in returning nearest value in each row.
One value from all:
data=data.flatten()
print data[(np.fabs(data-6.6)).argmin(axis=0)]
index position from each row:
ip = map(lambda x:(np.fabs(x-6.6)).argmin(axis=0), data)
This is the simplest way I think.
>>> data = np.array([[2.0, 3.0, 6.5, 6.5, 12.0],[1,2,3,4,5]], dtype=float)
>>> data2 = np.fabs(data - 6.6)
>>> np.unravel_index(data2.argmin(), data2.shape)
(0, 2)
See np.argmin
and np.unravel_index
function.