代码之家  ›  专栏  ›  技术社区  ›  blonc

使用Numpy argmax计数vs for循环

  •  0
  • blonc  · 技术社区  · 4 年前

    我目前使用类似的代码来确定比较

    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
    

    结果 counter 幅度将是 7 。然而,这对大型数据阵列来说是非常费力的。所以,我一直在寻找解决方案,并想出了 np.argmax() ,但似乎存在问题。例如以下内容:

    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)
    

    这将获得输出 1 ,就像 argmax 假设。。但我想让它输出 7. 。是否有其他方法可以为if语句提供类似的输出?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Ali_Sh    4 年前

    你可以得到一个布尔数组 high >= number 使用NumPy:

    list_of_numbers = [29800.0, 29795.0, 29795.0, 29740.0, 29755.0, 29745.0]
    high = 29980.0
    lookback = 10
    
    boolean_arr = np.less_equal(np.array(list_of_numbers), high)
    

    然后找到第一个在哪里 错误 论点中的满足 break 条件。此外,为了考虑对抗,您可以使用 np.cumsum 布尔数组 并找到满足指定条件的第一个自变量 回环 巨大因此,结果将是之间的较小值 break_arr lookback_lim :

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

    如果你 list_of_numbers 没有比您指定的更大的值 高的 的限制 break_arr 指定的 回环 超过中的值 np.cumsum(boolean_arr) 对于 lookback_lim ,上述代码将陷入如下错误,与有关 np.where :

    IndexError:索引0超出大小为0的轴0的界限

    可以由处理 try-except if 语句,例如:

    try:
        break_arr = np.where(boolean_arr == False)[0][0] + 1
    except:
        break_arr = len(boolean_arr) + 1
    
    try:
        lookback_lim = np.where(np.cumsum(boolean_arr) == lookback)[0][0] + 1
    except:
        lookback_lim = len(boolean_arr) + 1
    
        2
  •  1
  •   Ali_Sh    4 年前

    你倒签的还不到,不是吗?以下内容应作为for循环使用:

    print(np.min([np.sum(np.array(list_of_numbers) < high) + 1, lookback]))
    
        3
  •  0
  •   Golden Lion    4 年前

    回顾可以使用shift来完成。累计数可以用来得到一个连续的总数。查询可以用作筛选器