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
5
  • Was there more to your code? Commented Oct 14, 2015 at 2:30
  • 1
    numpy.where(a == 54) is probably what you are looking for Commented Oct 14, 2015 at 2:34
  • Possible duplicate of Is there a Numpy function to return the first index of something in an array? Commented Oct 14, 2015 at 2:35
  • What is your expected output if 54 shows up more than once in the array? Commented Oct 14, 2015 at 2: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? Commented Oct 14, 2015 at 2:59

1 Answer 1

3
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)]
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.