0

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
Charles Truluck
  • 961
  • 1
  • 7
  • 28
Riggun
  • 195
  • 15
  • Was there more to your code? – Hayley Guillou Oct 14 '15 at 02:30
  • 1
    `numpy.where(a == 54)` is probably what you are looking for – Akavall Oct 14 '15 at 02:34
  • Possible duplicate of [Is there a Numpy function to return the first index of something in an array?](http://stackoverflow.com/questions/432112/is-there-a-numpy-function-to-return-the-first-index-of-something-in-an-array) – paisanco Oct 14 '15 at 02:35
  • What is your expected output if 54 shows up more than once in the array? – Akavall Oct 14 '15 at 02:36
  • Yes I need just index of equal value in array. How can I use numpy.where if my array name is my_array and value i need to search is 54? – Riggun Oct 14 '15 at 02:59

1 Answers1

2
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)]
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • Yes your variant is just what I need it returns index of the element but array I use is named array with mixed values. new_array = np.core.records.fromrecords([(data[0],data[1],data[2],data[3],data[4],data[5],NDate)],names='Date, Name, Age, Start, End,Avg,NDate',formats='S10,f8,f8,f8,f8,f8,f16'). and when i use someting like temp = np.where(new_array == 7.43) it returns me ""(array([], dtype=int32),) but not the index of the value. But 7.43 value exists in array. – Riggun Oct 14 '15 at 07:01