gpt4 book ai didi

python - 查找介于给定范围之间的索引

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:47 25 4
gpt4 key购买 nike

我想在 dataXdataY 中找到边界 (B4X1, B4X2) 和 (B4Y1, B4Y2) 之间的元素

import numpy as np 

B4X1 = 50.
B4X2 = 60.


B4Y1 = 150.
B4Y2 = 160.

dataX = np.array([40, 25, 50, 60, 55])
dataY = np.array([140, 125, 150, 160, 155])

Expected result is:

result = array([False, False, False, False, True], dtype=bool)

怎样做会更快?

我这样做了:

OK = (B4X1 < dataX < B4X2) & (B4Y1 < dataY < B4Y2)

print OK

但是报错:

Traceback (most recent call last):
File "C:\Users\je\Desktop\test.py", line 14, in <module>
OK = (B4X1 < dataX < B4X2) & (B4Y1 < dataY < B4Y2)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

最佳答案

快捷符号B4X1 < dataX < B4X2不起作用。

您需要执行以下操作:

OK = (B4X1 < dataX) & (dataX < B4X2) & (B4Y1 < dataY) & (dataY < B4Y2)

编辑:

由于时间被提出来了:

In [23]: dataX = np.random.randint(200, size=100)

In [24]: dataY = np.random.randint(200, size=100)

In [25]: %timeit OK = (B4X1 < dataX) & (dataX < B4X2) & (B4Y1 < dataY) & (dataY < B4Y2)
10000 loops, best of 3: 23.6 µs per loop

In [26]: %timeit OK = np.logical_and.reduce([B4X1<dataX,dataX<B4X2,B4Y1<dataY,dataY<B4Y2])
10000 loops, best of 3: 26.7 µs per loop

In [27]: %timeit for i in dataX: OK = (B4X1 < i and i < B4X2) and (B4Y1 < i and i < B4Y2)
1000 loops, best of 3: 449 µs per loop

In [28]: %timeit for i in dataX: OK = (B4X1 < i and i < B4X2) and (B4Y1 < i and i < B4Y2)
1000 loops, best of 3: 329 µs per loop

关于python - 查找介于给定范围之间的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30962555/

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