【问题标题】:How find values in an array that meet two conditions using Python如何使用Python在满足两个条件的数组中查找值
【发布时间】:2011-03-15 23:32:52
【问题描述】:

我有一个数组

a=[1,2,3,4,5,6,7,8,9]

我想找到满足两个条件的元素 s 的索引,即

a>3 and a<8
ans=[3,4,5,6]
a[ans]=[4,5,6,7]

我可以使用numpy.nonzero(a&gt;3)numpy.nonzero(a&lt;8) 但不是 numpy.nonzero(a&gt;3 and a&lt;8) 给出错误:

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

当我尝试使用 anyall 时,我得到了同样的错误。 是否可以结合两个条件测试来获得答案?

【问题讨论】:

  • 为什么你需要numpy,你不能这样!过滤器(λ a: 3
  • @shahjapan - 可能是因为他们需要提高 numpy 数组的速度,因为他们可能真的有一个大得多的数据集。

标签: python find numpy


【解决方案1】:
numpy.nonzero((a > 3) & (a < 8))

& 执行元素级布尔值与。

【讨论】:

    【解决方案2】:

    另一种选择(我最终使用)是numpy.logical_and

    choice = numpy.logical_and(np.greater(a, 3), np.less(a, 8))
    numpy.extract(choice, a)
    

    【讨论】:

      【解决方案3】:

      如果你使用numpy数组,你可以直接使用'&amp;'而不是'and'。

      a=array([1,2,3,4,5,6,7,8,9])
      a[(a>3) & (a<8)]
      ans=array([3,4,5,6])
      

      【讨论】:

        猜你喜欢
        • 2021-05-15
        • 2020-12-21
        • 2021-05-27
        • 2019-11-11
        • 2020-05-11
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多