【问题标题】:What is the fastest way of extracting indexes of non "-1"s from an array?从数组中提取非“-1”索引的最快方法是什么?
【发布时间】:2019-03-09 18:33:45
【问题描述】:

我有一个尺寸为 1500 x 3300 的 numpy 数组。我想获取所有值大于 0.40 的值的索引。

例如一个子数组:

a = [0,0.5,0.4,-1,-1,0.9,0.3,-1,0.7]

期望的结果: [0,1,5,8]

我已经编写了以下代码,但是运行起来需要很多时间。在 1500 x 3300 维度的数组上运行需要 20 分钟。

def non_zero(lst):
    """ return indexes of items which are not -1 and value is greater than 0.40 """
    return [i for i, e in enumerate(lst) if e > 0.40]

什么是最快的替代方法?

【问题讨论】:

    标签: python list numpy


    【解决方案1】:

    直接在二维数组中尝试以下操作:

    i, j = np.where(np.array(lst) > 0.4)
    

    【讨论】:

      【解决方案2】:

      您可以使用np.argwhere 获取索引。

      import numpy as np
      idx = np.argwhere(a != -1 & a > 0.4)
      

      当然,a!= -1 不是必需的..

      【讨论】:

        【解决方案3】:
        import numpy as np    
        np.where(np.array(a) > 0.40)[0].tolist()
        

        值 > 0.40 当然是 > -1

        我还假设“a”是数字列表(不是列表列表)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多