I have an array for example:
[1 2 3 4
2 3 4 0
5 4 0 6]
And I want to find the indexes of all the values that are closer to to the value 3.9 (in my example,4)
I tried using :
import numpy as np
def find_nearest(array, value):
idx = (np.abs(array - value)).argmin()
and
np.where(array== array.min())
but none of the options gives me the correct answer.
I do excpect to get:
(3,1),(1,2),(2,1)
In my original code, I iterate an array with the shape of 3648X5472 so "FOR" loops might be too heavy.
hope to get some help here, thank you
>Solution :
You can use:
a = np.array([[1, 2, 3, 4],
[2, 3, 4, 0],
[5, 4, 0, 6]])
v = 3.9
b = abs(a-v)
xs, ys = np.where(b == np.min(b))
output:
>>> xs
array([0, 1, 2])
>>> ys
array([3, 2, 1])
Alternative output:
>>> np.c_[np.where(b == np.min(b))]
array([[0, 3],
[1, 2],
[2, 1]])
# or
>>> np.argwhere(b==np.min(b))