如何返回numpy数组中两个数之间的值的索引

2024-09-26 22:44:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想返回python numpy数组中两个值之间的所有值的索引。这是我的代码:

inEllipseIndFar = np.argwhere(excessPathLen * 2 < ePL < excessPathLen * 3)

但它返回一个错误:

inEllipseIndFar  = np.argwhere((excessPathLen * 2 < ePL < excessPathLen * 3).all())
ValueError: The truth value of an array with more than one element is ambiguous. Use 
a.any() or a.all()

我想知道是否有一种方法可以在不遍历数组的情况下执行此操作。谢谢!


Tags: ofthe代码numpyvalue错误np数组
2条回答

通过使用圆括号和正确的操作,可以组合多个布尔表达式:

In [1]: import numpy as np

In [2]: A = 2*np.arange(10)

In [3]: np.where((A > 2) & (A < 8))
Out[3]: (array([2, 3]),)

还可以将np.where的结果设置为变量以提取值:

In [4]: idx = np.where((A > 2) & (A < 8))

In [5]: A[idx]
Out[5]: array([4, 6])

由于> < =返回屏蔽数组,因此可以将它们相乘以获得所需的效果(基本上是逻辑和):

>>> import numpy as np
>>> A = 2*np.arange(10)
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

>>> idx = (A>2)*(A<8)
>>> np.where(idx)
array([2, 3])

相关问题 更多 >

    热门问题