【问题标题】:Checking consecutive positive values of a Numpy Array Python检查 Numpy Array Python 的连续正值
【发布时间】:2021-09-04 19:19:33
【问题描述】:

我如何编写一个函数来显示从数组A, B, C 的末尾到开头有多少个连续的正值。所以数组B 从结尾3,5 开始有2 个正连续值,因此为什么会导致2 的输出。

import numpy as np

A = np.array([2,5,44,-12,3,-5])
B = np.array([2,5,44,-12,3,5])
C = np.array([2,5,44,12,3,5])

预期输出:

0
2
6

【问题讨论】:

    标签: arrays python-3.x numpy sorting indexing


    【解决方案1】:

    反转数组的正性掩码上的累积最小值:

    def num_consec_pos_from_end(arr):
        return np.minimum.accumulate(arr[::-1] > 0).sum()
    

    arr[::-1] > 0 将给出一个布尔数组,我们需要Trues 的数量直到False。因为False 比较小于True,所以minimum.accumulate 将一劳永逸地更改为False,如果它看到一个。然后我们对结果数组求和,即对输出的 True 值求和,

    得到

    >>> num_consec_pos_from_end(A)
    0
    
    >>> num_consec_pos_from_end(B)
    2
    
    >>> num_consec_pos_from_end(C)
    6
    

    【讨论】:

      【解决方案2】:

      你可以使用:

      def count_last_pos(arr):
          d = (arr>0)[::-1]
          return (d.cumsum() * d.cumprod()).max()
      
      count_last_pos(A)
      # 0 
      count_last_pos(B)
      # 2
      count_last_pos(C)
      # 6
      

      【讨论】:

        【解决方案3】:

        可以先找到最后一个负值的索引,然后从数组长度中减去:

        def count_trailing_positive(a):
            idx = np.flatnonzero(a < 0)        # find all indices of negative values
            if len(idx) > 0:
                return len(a) - idx[-1] - 1    # subtract last index from array length
            else:
                return len(a)
        
        count_trailing_positive(A)
        # 0
        count_trailing_positive(B)
        # 2
        count_trailing_positive(C)
        # 6
        

        【讨论】:

          猜你喜欢
          • 2021-07-14
          • 2018-12-20
          • 2021-08-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多