Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array print index of certain value

Given a numpy array

A = np.array([[[29, 64, 83],
               [17, 92, 38],
               [67, 34, 20]],
              [[73, 28, 45],
               [19, 84, 61],
               [22, 63, 49]],
              [[48, 30, 13],
               [11, 52, 86],
               [62, 25, 12]]])

I want the index of a certain value, say 63

There is no possibility that the value will be duplicated or missing

I did

idx = np.where(A == 63)

print(idx)

I got

(array([1], dtype=int32), array([2], dtype=int32), array([1], dtype=int32))

What I want is

[1, 2, 1]

as a list or other iterable without all that array, dtype=int32 etc.

How do I do this?

like image 499
Barry Andersen Avatar asked Jul 31 '14 19:07

Barry Andersen


People also ask

How do you find the index of an element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

What is a correct method to search for a certain value in an array?

You can search an array for a certain value, and return the indexes that get a match. To search an array, use the where() method.


1 Answers

If you want to get a numpy array back, just use the concatenate function:

In [30]: np.concatenate(idx)
Out[30]: array([1, 2, 1])

If you really have your heart set on a Python list, then just:

In [31]: np.concatenate(idx).tolist()
Out[31]: [1, 2, 1]
like image 181
chrisaycock Avatar answered Sep 28 '22 17:09

chrisaycock