我有一个名为dist的距离数组。我想选择一个范围内的dist。

 dists[(np.where(dists >= r)) and (np.where(dists <= r + dr))]

但是,这只选择条件

 (np.where(dists <= r + dr))

如果我使用临时变量按顺序执行命令,它可以很好地工作。为什么上面的代码不能工作,我如何让它工作?


当前回答

我已经算出了这个简单的例子

import numpy as np

ar = np.array([3,4,5,14,2,4,3,7])

print [X for X in list(ar) if (X >= 3 and X <= 6)]

>>> 
[3, 4, 5, 4, 3]

其他回答

我喜欢用np。向量化这类任务。考虑以下几点:

>>> # function which returns True when constraints are satisfied.
>>> func = lambda d: d >= r and d<= (r+dr) 
>>>
>>> # Apply constraints element-wise to the dists array.
>>> result = np.vectorize(func)(dists) 
>>>
>>> result = np.where(result) # Get output.

你也可以用np。Argwhere而不是np。其中为明确的输出。

这应该可以工作:

dists[((dists >= r) & (dists <= r+dr))]

Try:

np.intersect1d(np.where(dists >= r)[0],np.where(dists <= r + dr)[0])

公认的答案很好地解释了这个问题。但是,应用多个条件的更Numpythonic方法是使用numpy逻辑函数。在这种情况下,您可以使用np.logical_and:

np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))

我已经算出了这个简单的例子

import numpy as np

ar = np.array([3,4,5,14,2,4,3,7])

print [X for X in list(ar) if (X >= 3 and X <= 6)]

>>> 
[3, 4, 5, 4, 3]