Reputation: 315
Does Numpy have a function for quick search of element in 2D array and return its indexes? Mean for example:
a=54
array([[ 0, 1, 2, 3],
[ 4, 5, 54, 7],
[ 8, 9, 10, 11]])
So equal value will be array[1][2]
.
Of course I can make it using simple loops- but I want something similar to:
if 54 in arr
Upvotes: 0
Views: 1827
Reputation: 86168
In [4]: import numpy as np
In [5]: my_array = np.array([[ 0, 1, 2, 3],
[ 4, 5, 54, 7],
[8, 54, 10, 54]])
In [6]: my_array
Out[6]:
array([[ 0, 1, 2, 3],
[ 4, 5, 54, 7],
[ 8, 54, 10, 54]])
In [7]: np.where(my_array == 54) #indices of all elements equal to 54
Out[7]: (array([1, 2, 2]), array([2, 1, 3])) #(row_indices, col_indices)
In [10]: temp = np.where(my_array == 54)
In [11]: zip(temp[0], temp[1]) # maybe this format is what you want
Out[11]: [(1, 2), (2, 1), (2, 3)]
Upvotes: 3