1

How can i find the indices of elements in a Numpy array which satisfy multiple criteria?

Example: The function numpy.nonzero lets me find the indices according to some criterion:

In [1]: from numpy import *
In [2]: a = array([1,0,1,-1])
In [5]: nonzero(a != 0)
Out[5]: (array([0, 2, 3]),)

However, giving multiple criteria like this does not work:

In [6]: nonzero((a != 0) and (a < 0))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/cls/<ipython-input-6-85fafffc5d1c> in <module>()
----> 1 nonzero((a != 0) and (a < 0))

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

In MATLAB, it's possible to write:

find((d != 0) & (d < 0))

How can I do this with Numpy?

1 Answer 1

4

IIUC, you can use & instead of and:

>>> from numpy import *
>>> a = array([1,0,1,-1])
>>> nonzero(a!=0)
(array([0, 2, 3]),)
>>> nonzero((a != 0) and (a < 0))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> nonzero((a != 0) & (a < 0))
(array([3]),)
>>> where((a != 0) & (a < 0))
(array([3]),)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. What does "IIUC" mean?

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.