简体   繁体   English

使用 Numpy argmax 来计数 vs for 循环

[英]using Numpy argmax to count vs for loop

I currently use something like the similar bit of code to determine comparison我目前使用类似的代码来确定比较

list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
high = 29980.0
lookback = 10
counter = 1

for number in list_of_numbers:
    if (high >= number) \
    and (counter < lookback):
        counter += 1
    else:
        break

this will give you the output 7 and functions as you expect it to.这将为您提供 output 7 并按照您的预期运行。 however is very taxing on large data arrays.然而,对大数据 arrays 非常费力。 So I looked for a solution and came up with np.argmax() but there seems to be an issue.所以我寻找了一个解决方案并想出了 np.argmax() 但似乎有一个问题。 For example the following:例如以下:

list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
np_list = np.array(list_of_numbers)
high = 29980.0

print(np.argmax(np_list > high) + 1)

this will output 1, just like armax is suppose to.. but I want it to output 7. Is there another method to do this that will give me similar output to the if statement?这将是 output 1,就像 armax 假设的那样.. 但我想要它到 output 7. 有没有另一种方法可以做到这一点,会给我类似的 Z78E6221F6393D13566681DB39F14CE 到 if 语句

You can get a boolean array for where high >= number using NumPy, and then finding where is the first False argument in that to satisfy break condition in your code.:您可以使用 NumPy 获得 boolean 数组,其中high >= number ,然后找到其中的第一个False参数以满足代码中的break条件。:

boolean_arr = np.less_equal(np.array(list_of_numbers), high)
break_arr = np.where(boolean_arr == False)[0][0] + 1

To consider countering, you can use np.cumsum on the boolean array and find the first argument that satisfying specified lookback magnitude.要考虑反击,您可以在boolean 数组上使用np.cumsum并找到满足指定回溯幅度的第一个参数。 So, the result will be smaller value between break_arr and lookback_lim :因此,结果将是break_arrlookback_lim之间的较小值:

lookback_lim = np.where(np.cumsum(boolean_arr) == lookback)[0][0]
result = min(break_arr, lookback_lim)

You have you less than sign backwards, no?你有你不到向后签名,不是吗? The following should word the same as your for-loop:以下内容应与您的 for 循环相同:

print(np.min([np.sum(np_list < high)+1, lookback]))

A look back can be accomplished using shift.可以使用 shift 来完成回顾。 A cumcount can be used to get a running total. cumcount 可用于获取运行总计。 A query can be used as a filter查询可以用作过滤器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM