python中if函数多个条件怎么用_python - Numpy函数的多个条件

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

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

它只创建一个布尔数组,在我看来更容易阅读,因为它说,and或True中的np.where? (虽然我重新定义了np.where作为您感兴趣的区域的中心而不是开头,所以and)但是这并没有回答您的问题。

你的问题的答案:

如果您只是想过滤掉不符合您标准的and元素,那么您实际上并不需要np.where:

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

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

或者,如果您出于某种原因想要使用np.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. ])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值