1

如何在 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 做到这一点?

4

1 回答 1

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]),)
于 2012-05-14T16:28:43.037 回答