【问题标题】:Slicing and getting the max value with Numpy Python使用 Numpy Python 切片并获取最大值
【发布时间】:2021-01-28 04:34:20
【问题描述】:

我正在尝试使用 numpy 编写代码,它输出索引之间的最大值。我认为使用argmax 可能是可用的。但是我不知道如何在不使用 python 循环的情况下使用切片。如果有一个熊猫功能,它也可以使用。我想让计算尽可能快。

list_ = np.array([9887.89, 9902.99, 9902.99, 9910.23, 9920.79, 9911.34, 9920.01, 9927.51, 9932.3, 9932.33, 9928.87, 9929.22, 9929.22, 9935.24, 9935.24, 9935.26, 9935.26, 9935.68, 9935.68, 9940.5])
indexes = np.array([0, 5, 10, 19])

预期结果:

Max number between index(0 - 5):  9920.79 at index 5
Max number between index(5 - 10): 9932.33 at index 10
Max number between index(10 - 19): 9940.5 at index 19

【问题讨论】:

    标签: python numpy indexing


    【解决方案1】:

    你可以直接使用reduceat你的数组,而不需要拼接/拆分它:

    np.maximum.reduceat(list_,indexes[:-1])
    

    输出:

    array([9932.33, 9929.22, 9940.5 ])
    

    【讨论】:

      【解决方案2】:

      假设索引数组中指定了第一个(零)索引和最后一个索引,

      import numpy as np
      
      list_ = np.array([9887.89, 9902.99, 9902.99, 9910.23, 9920.79, 9911.34, 9920.01, 9927.51, 9932.3, 9932.33, 9928.87, 9929.22, 9929.22, 9935.24, 9935.24, 9935.26, 9935.26, 9935.68, 9935.68, 9940.5])
      indexes = np.array([0, 5, 10, 19])
      
      chunks = np.split(list_, indexes[1:-1])
      print([c.max() for c in chunks])
      
      max_ind = [c.argmax() for c in chunks]
      print(max_ind + indexes[:-1])
      

      没有必要让每个块都具有相同的大小和任意指定的索引。因此,numpy 的矢量化优势将会以一种或另一种方式丢失(因为你不能有一个 numpy 数组,其中每个元素在内存中的大小不同,这也具有矢量化的所有优势)。

      我认为至少需要一个 for 循环。但是,您可以使用 split 来使拆分成为 numpy 优化的操作。

      【讨论】:

      • 谢谢它的工作有没有办法我也可以获得最大值的索引?
      • 原始数组中的索引对吗?不是子块?
      • 修改了答案以打印出索引。
      • 谢谢,如果我可以摆脱列表理解,我会尝试找到一种方法,而不是代码制作得非常好,非常感谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      相关资源
      最近更新 更多