Get the positions of the array where you find a value with numpy.where


I have an array of the form:

array = ['A', 'D', 'A', 'A', 'A', 'D', 'A', 'A', 'D', 'A']

And I need to get the positions of the array where I find 'D' . What I'm trying to do is:

d_pos[numpy.where(array == 'D')]

But I get the following error:

TypeError: list indices must be integers, not tuple

Searching I have seen that numpy.where use it looking for numerical values, but it is not clear to me if it also works looking for letters in this case.

And another thing, actually the values in the array when I print them appear in unicode, like this:

array = [u'A', u'D', u'A', u'A', u'A', u'D', u'A', u'A', u'D', u'A']

And I do not know if the error is due to the format or the numpy.where

Does anyone know what I'm doing wrong?

asked by Eve2 21.09.2016 в 20:34

1 answer


In your code there are several things that seem to be wrong:

  • On the one hand, to be able to compare all the elements of array to know if they are equal to 'D' you need that array is really a numpy.array . As you are defining it is a list.

  • On the other hand, numpy.where returns a tuple with a np.array with the positions where the condition is met and dtype of numpy.array .

If we put the two previous things together we have:

>>> import numpy as np
>>> array = ['A', 'D', 'A', 'A', 'A', 'D', 'A', 'A', 'D', 'A']
>>> print(np.where(array == 'D'))
(array([], dtype=int32),)

In the numpy.where we are entering a condition that is not met, a pure list of python is not equal to the string 'D' and, therefore, numpy.where returns the tuple but with the array of empty positions .

In your case, at d_pos you are passing a tuple with which to index and the error tells you that you can not use tuples to index.

We will slightly correct the code to see if it works:

>>> import numpy as np
>>> array = np.array(['A', 'D', 'A', 'A', 'A', 'D', 'A', 'A', 'D', 'A'])
>>> print(np.where(array == 'D'))
(array([1, 5, 8], dtype=int32),)

Now we see with np.where and it returns a tuple that contains the array of positions without being empty. If we want to use it in d_pos we can do:

>>> indices = np.where(array == 'D')[0] # fíjate en el cero final
>>> d_pos[indices]

In the line of indices I'm left with the first part of the tuple that returns np.where , which is the one that contains the positions you were looking for.

answered by 21.09.2016 в 22:58