我有一个叫做dists的距离数组。我想选择介于两个值之间的dists。为此,我编写了以下代码行:
dists[(np.where(dists >= r)) and (np.where(dists <= r + dr))]
但是,这仅为条件选择
(np.where(dists <= r + dr))
如果我使用一个临时变量按顺序执行这些命令,它会工作得很好。为什么上面的代码不能工作,我如何让它工作?
干杯
发布于 2015-07-15 01:49:55
公认的答案很好地解释了这个问题。但是,应用多个条件的更具数值性的方法是使用numpy logical functions。在这种情况下,您可以使用np.logical_and
np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))
发布于 2017-11-09 14:32:09
我喜欢使用np.vectorize
来完成这样的任务。请考虑以下几点:
>>> # 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.where
来获得清晰的输出。
发布于 2019-06-24 16:17:15
尝试:
import numpy as np
dist = np.array([1,2,3,4,5])
r = 2
dr = 3
np.where(np.logical_and(dist> r, dist<=r+dr))
输出:(array(2,3,4),)
您可以查看Logic functions了解更多详细信息。
https://stackoverflow.com/questions/16343752
复制相似问题