Reputation: 75
**Made a mistake in the original version. The dimensions of arrays are unequal now. This is a stupid question but I can't find the right answer. How do you index the closest number in a 2d numpy array? Let say we have
e = np.array([[1, 2], [4, 5, 6]])
I want to locate the indices of values closest to 2, such that it return
array([1, 0])
Many thanks!
Upvotes: 1
Views: 3377
Reputation: 432
Though this is an old question, for "rectangular" arrays as in the other answers it's a one-liner
import numpy as np
e = np.array([[1, 2, 3], [4, 5, 6]])
val = 2.4
nearest = np.unravel_index(np.argmin(np.abs(e - val), axis=None), e.shape)
nearest
(0, 1)
Upvotes: 0
Reputation: 1553
Usually you would use np.argwhere(e == 2)
:
In [4]: e = np.array([[1,2,3],[4,5,6]])
In [6]: np.argwhere(e == 2)
Out[6]: array([[0, 1]])
In case you really need the output you specified, you have to add an extra [0]
In [7]: np.argwhere(e == 2)[0]
Out[7]: array([0, 1])
However, the input you provided is not a standard numeric array but an object
array because len(e[0]) != len(e[1])
:
In [1]: e = np.array([[1,2],[4,5,6]])
In [3]: e
Out[3]: array([list([1, 2]), list([4, 5, 6])], dtype=object)
This makes numpy much less useful and efficient. You would have to resort to something like:
In [26]: res = []
...: for i, f in enumerate(e):
...: g = np.array(f)
...: w = np.argwhere(g==2)
...: if len(w):
...: res += [(i, v) for v in w]
...: res = np.array(res)
Assuming this was a typo and if you are interested in the value closest to 2 even if 2 is not present, you would have to do something like:
In [35]: np.unravel_index((np.abs(e - 2.2)).argmin(), e.shape)
Out[35]: (0, 1)
Here I chose 2.2 as an example value.
Upvotes: 3
Reputation: 1343
This can be done by defining a function that works on a 1D array and applying it over the rows of the 2D array:
e = np.array([[1,2,3], [4,5,6]])
# function to find position of nearest value in 1D array
def find_nearest(a, val):
return np.abs(a - val).argmin()
# apply it
np.apply_along_axis(find_nearest, axis = 1, arr = e, val = 2)
Upvotes: 1