Numpy where 函数多个条件

新手上路,请多包涵

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

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

但是,这仅针对条件进行选择

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

如果我使用临时变量按顺序执行命令,它就可以正常工作。为什么上面的代码不起作用,我该如何让它起作用?

原文由 user1654183 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 984
2 个回答

您的特定情况下,最好的方法就是将您的两个标准更改为一个标准:

 dists[abs(dists - r - dr/2.) <= dr/2.]

它只创建一个布尔数组,在我看来更容易阅读,因为它说, distdrr ? (虽然我会重新定义 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 值。 If a and b are both True values, then a and b returns 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. ])

原文由 askewchan 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 Mazdak 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏