【问题标题】:Finding elements in a numpy array with multiple criteria在具有多个条件的 numpy 数组中查找元素
【发布时间】:2012-05-14 16:24:53
【问题描述】:

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

【问题讨论】:

    标签: numpy python-3.x


    【解决方案1】:

    IIUC,你可以用&amp;代替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]),)
    

    【讨论】:

    • 谢谢。 “IIUC”是什么意思?
    猜你喜欢
    • 2020-01-06
    • 2021-05-12
    • 2018-08-14
    • 1970-01-01
    • 2019-12-06
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多