gpt4 book ai didi

python - Numpy where 函数多个条件

转载 作者:IT老高 更新时间:2023-10-28 21:07:04 25 4
gpt4 key购买 nike

我有一个名为 dists 的距离数组。我想选择一个范围内的 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.]

它只创建一个 bool 数组,在我看来更容易阅读,因为它说 is distdrr? (虽然我会将 r 重新定义为您感兴趣区域的中心而不是开始,所以 r = r + dr/2。) 但这并不能回答你的问题。


您的问题的答案:
如果您只是想过滤掉 dists 中不符合您条件的元素,您实际上并不需要 where:

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

因为 & 会给你一个元素的 and (括号是必要的)。

或者,如果你出于某种原因确实想使用 where,你可以这样做:

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

原因:
它不起作用的原因是 np.where 返回索引列表,而不是 bool 数组。您试图在两个数字列表之间获取 and,这当然没有您期望的 True/False 值。如果 ab 都是 True 值,则 a 和 b 返回 b .所以说像 [0,1,2] 和 [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]),)

您期望比较的只是 bool 数组,例如

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)

现在您可以在组合 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. ])

或者简单地使用 fancy indexing 用 bool 数组索引原始数组

In [241]: dists[(dists >= r) & (dists <= r + dr)]
Out[241]: array([ 5. , 5.5, 6. ])

关于python - Numpy where 函数多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16343752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com