如何在Numpy数组中找到满足多个条件的元素索引?
示例:函数numpy.nonzero
允许我根据某个标准找到索引:
In [1]: from numpy import *
In [2]: a = array([1,0,1,-1])
In [5]: nonzero(a != 0)
Out[5]: (array([0, 2, 3]),)
但是,提供这样的多个标准不起作用:
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()
在MATLAB中,可以写:
find((d != 0) & (d < 0))
我怎么能用Numpy做到这一点?
答案 0 :(得分:4)
IIUC,您可以使用&
代替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]),)