【问题标题】:Numpy: find index of the elements within rangeNumpy:查找范围内元素的索引
【发布时间】:2012-12-01 21:26:30
【问题描述】:

我有一个 numpy 数组,例如,

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  

我想查找特定范围内元素的所有索引。例如,如果范围是 (6, 10),则答案应该是 (3, 4, 5)。有没有内置函数可以做到这一点?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您可以使用np.where 获取索引和np.logical_and 设置两个条件:

    import numpy as np
    a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
    
    np.where(np.logical_and(a>=6, a<=10))
    # returns (array([3, 4, 5]),)
    

    【讨论】:

    • 顺便说一句,np.nonzero(np.logical_and(a&gt;=6, a&lt;=10)) 也是如此。
    • 还有np.where((a &gt; 6) &amp; (a &lt;= 10))
    • 似乎不太适合多维数组
    • @ELinda np.logical_and 比 &amp; 快一点。而且np.where 比np.nonzero 快。
    • 一个不错的解决方案,因为它也适用于 pandas 数据框。语法相同,只需将a 更改为df
    【解决方案2】:

    正如@deinonychusaur 的回复,但更紧凑:

    In [7]: np.where((a >= 6) & (a <=10))
    Out[7]: (array([3, 4, 5]),)
    

    【讨论】:

    • 不错。如果a 是一个numpy 数组,你也可以使用a[(a &gt;= 6) &amp; (a &lt;= 10)]。
    • 以防有人像我一样对评论的措辞感到困惑:这不适用于普通列表,只有当 a 是一个 numpy 数组时
    【解决方案3】:

    我想我会添加这个,因为您给出的示例中的 a 已排序:

    import numpy as np
    a = [1, 3, 5, 6, 9, 10, 14, 15, 56] 
    start = np.searchsorted(a, 6, 'left')
    end = np.searchsorted(a, 10, 'right')
    rng = np.arange(start, end)
    rng
    # array([3, 4, 5])
    

    【讨论】:

      【解决方案4】:
      a = np.array([1,2,3,4,5,6,7,8,9])
      b = a[(a>2) & (a<8)]
      

      【讨论】:

        【解决方案5】:

        答案总结

        为了了解什么是最佳答案,我们可以使用不同的解决方案进行一些计时。 不幸的是,这个问题没有很好地提出,所以有不同问题的答案,在这里我试图指出同一个问题的答案。给定数组:

        a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
        

        答案应该是元素在一定范围内的索引,我们假设包括在内,在本例中为 6 和 10。

        answer = (3, 4, 5)
        

        对应值6、9、10。

        要测试最佳答案,我们可以使用此代码。

        import timeit
        setup = """
        import numpy as np
        import numexpr as ne
        
        a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
        # or test it with an array of the similar size
        # a = np.random.rand(100)*23 # change the number to the an estimate of your array size.
        
        # we define the left and right limit
        ll = 6
        rl = 10
        
        def sorted_slice(a,l,r):
            start = np.searchsorted(a, l, 'left')
            end = np.searchsorted(a, r, 'right')
            return np.arange(start,end)
        """
        
        functions = ['sorted_slice(a,ll,rl)', # works only for sorted values
        'np.where(np.logical_and(a>=ll, a<=rl))[0]',
        'np.where((a >= ll) & (a <=rl))[0]',
        'np.where((a>=ll)*(a<=rl))[0]',
        'np.where(np.vectorize(lambda x: ll <= x <= rl)(a))[0]',
        'np.argwhere((a>=ll) & (a<=rl)).T[0]', # we traspose for getting a single row
        'np.where(ne.evaluate("(ll <= a) & (a <= rl)"))[0]',]
        
        functions2 = [
           'a[np.logical_and(a>=ll, a<=rl)]',
           'a[(a>=ll) & (a<=rl)]',
           'a[(a>=ll)*(a<=rl)]',
           'a[np.vectorize(lambda x: ll <= x <= rl)(a)]',
           'a[ne.evaluate("(ll <= a) & (a <= rl)")]',
        ]
        
        rdict = {}
        for i in functions:
            rdict[i] = timeit.timeit(i,setup=setup,number=1000)
            print("%s -> %s s" %(i,rdict[i]))
        
        print("Sorted:")
        for w in sorted(rdict, key=rdict.get):
            print(w, rdict[w])
        

        结果

        @EZLearner 指出,在下图中报告了一个小数组的结果(在顶部是最快的解决方案),它们可能会因数组的大小而异。 sorted slice 对于较大的数组可能更快,但它需要对数组进行排序,对于条目超过 10 M 的数组ne.evaluate 可能是一个选项。因此,使用与您的数组大小相同的数组执行此测试总是更好:

        如果您想要提取值而不是索引,您可以使用函数执行测试2,但结果几乎相同。

        【讨论】:

        • 这些结果只适用于特定长度的数组(这里您选择了一个非常小的数组)。对于较大的数组,这些结果会迅速变化
        • @EZLearner 感谢您的反馈。我已经更新了答案。
        【解决方案6】:

        这段代码 sn-p 返回一个 numpy 数组中两个值之间的所有数字:

        a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56] )
        a[(a>6)*(a<10)]
        

        它的工作原理如下: (a>6) 返回一个带有 True (1) 和 False (0) 的 numpy 数组,(a

        a[...] 部分返回数组 a 的所有值,其中括号之间的数组返回 True 语句。

        当然,你可以通过说例如让这更复杂

        ...*(1-a<10) 
        

        类似于“and Not”语句。

        【讨论】:

          【解决方案7】:

          其他方法是:

          np.vectorize(lambda x: 6 <= x <= 10)(a)
          

          返回:

          array([False, False, False,  True,  True,  True, False, False, False])
          

          它有时对屏蔽时间序列、向量等很有用。

          【讨论】:

            【解决方案8】:
            a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
            np.argwhere((a>=6) & (a<=10))
            

            【讨论】:

              【解决方案9】:

              想将numexpr 添加到组合中:

              import numpy as np
              import numexpr as ne
              
              a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  
              
              np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
              # array([3, 4, 5], dtype=int64)
              

              仅适用于数百万的大型数组......或者如果您达到内存限制。

              【讨论】:

                【解决方案10】:

                这可能不是最漂亮的,但适用于任何维度

                a = np.array([[-1,2], [1,5], [6,7], [5,2], [3,4], [0, 0], [-1,-1]])
                ranges = (0,4), (0,4) 
                
                def conditionRange(X : np.ndarray, ranges : list) -> np.ndarray:
                    idx = set()
                    for column, r in enumerate(ranges):
                        tmp = np.where(np.logical_and(X[:, column] >= r[0], X[:, column] <= r[1]))[0]
                        if idx:
                            idx = idx & set(tmp)
                        else:
                            idx = set(tmp)
                    idx = np.array(list(idx))
                    return X[idx, :]
                
                b = conditionRange(a, ranges)
                print(b)
                

                【讨论】:

                  【解决方案11】:
                  s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]
                  
                  dic={}
                  
                  for i in range(0,len(s),10):
                      dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
                  print(dic)
                  
                  for keys,values in dic.items():
                      print(keys)
                      print(values)
                  

                  输出:

                  (0, 10)
                  [7, 2, 1, 3, 9, 5]
                  (20, 30)
                  [22, 26, 28, 21, 29, 23]
                  (30, 40)
                  [33, 39, 38, 32, 35, 30, 34]
                  (10, 20)
                  [11, 19, 15, 12, 13]
                  (40, 50)
                  [46, 43, 44, 49, 47, 45, 48]
                  (60, 70)
                  [69, 60, 63, 65, 66, 67, 62]
                  (50, 60)
                  [52, 57, 59, 58, 50, 56, 54, 55, 51]  
                  

                  【讨论】:

                    【解决方案12】:

                    您可以使用np.clip() 来实现相同的效果:

                    a = [1, 3, 5, 6, 9, 10, 14, 15, 56]  
                    np.clip(a,6,10)
                    

                    但是,它分别保存小于和大于 6 和 10 的值。

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2018-07-27
                      • 2013-10-08
                      • 1970-01-01
                      • 2019-05-04
                      • 2019-07-12
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多