脾气暴躁的地方
我有一个称为dists的距离数组。我想选择两个值之间的距离。我编写了以下代码行:
dists[(np.where(dists >= r)) and (np.where(dists <= r + dr))]
但是,这仅针对条件选择
(np.where(dists <= r + dr))
如果我使用临时变量按顺序执行命令,则可以正常工作。为什么上面的代码不起作用,如何使它起作用?
干杯
-
在 您的特定情况下 ,最好的方法 是 将两个条件更改为一个条件:
dists[abs(dists - r - dr/2.) <= dr/2.]
它仅创建一个布尔数组,在我看来是更易于阅读,因为它说,
是dist
内部的dr
还是r
?(尽管我将重新定义r
为您感兴趣的区域的中心,而不是开始的位置,所以r = r + dr/2.
)但这并不能回答您的问题。
问题的答案: 如果您只是想过滤出不符合标准的元素,则
实际上并不需要:where``dists
dists[(dists >= r) & (dists <= r+dr)]
因为
&
将会为您提供基本元素and
(必须带括号)。或者,如果您
where
出于某些原因要使用,可以执行以下操作:dists[(np.where((dists >= r) & (dists <= r + dr)))]
原因:
不起作用的原因是因为np.where
返回的是索引列表,而不是布尔数组。您试图and
在两个数字列表之间移动,这些数字当然没有您期望的True
/False
值。如果a
和b
都是两个True
值,则a and b
返回b
。所以说些什么[0,1,2] and [2,3,4]
只会给你[2,3,4]
。它在起作用:In [230]: dists = np.arange(0,10,.5) In [231]: r = 5 In [232]: dr = 1 In [233]: np.where(dists >= r) Out[233]: (array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),) In [234]: np.where(dists <= r+dr) Out[234]: (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),) In [235]: np.where(dists >= r) and np.where(dists <= r+dr) Out[235]: (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),)
您期望比较的只是布尔数组,例如
In [236]: dists >= r Out[236]: array([False, False, False, False, False, False, False, False, False, False, True, True, True, True, True, True, True, True, True, True], dtype=bool) In [237]: dists <= r + dr Out[237]: array([ True, True, True, True, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False], dtype=bool) In [238]: (dists >= r) & (dists <= r + dr) Out[238]: array([False, False, False, False, False, False, False, False, False, False, True, True, True, False, False, False, False, False, False, False], dtype=bool)
现在,您可以调用
np.where
组合的布尔数组:In [239]: np.where((dists >= r) & (dists <= r + dr)) Out[239]: (array([10, 11, 12]),) In [240]: dists[np.where((dists >= r) & (dists <= r + dr))] Out[240]: array([ 5. , 5.5, 6. ])
In [241]: dists[(dists >= r) & (dists <= r + dr)] Out[241]: array([ 5. , 5.5, 6. ])