【问题标题】:How to count the number of TRUE until a FALSE in numpy array?如何计算 TRUE 的数量,直到 numpy 数组中的 FALSE?
【发布时间】:2021-07-16 22:23:28
【问题描述】:

我正在尝试计算 numpy.array 中 True 值的数量,直到达到 False。

例如,如果你有

condition = np.array([True, True, True, False, 
    False, True, False, True, True, False, True])

那么想要的结果就是

np.array([3, 2, 1, 0, 0, 1, 0, 2, 1, 0, 1])

编辑:

Numpy first occurrence of value greater than existing value 不是我要问的,因为这是关于第一次满足条件的问题。我在问每次满足条件时连续满足多少次。 Find first sequence item that matches a criterion 也不起作用,因为我再次询问序列是否第一次满足条件。

【问题讨论】:

标签: python numpy boolean counting


【解决方案1】:
condition = np.array([True, True, True, False, 
    False, True, False, True, True, False, True])
    
r = []
c = 0

for x in reversed(condition):
  if x == False:
    c = 0
  else:
    c+=1
  r.append(c)
  
r.reverse()
print(np.array(r))

https://trinket.io/python3/a5bd54189b


更短的版本:

r = [0]
for x in reversed(condition):
  r.append(r[-1] + 1 if x else 0)

r.reverse()
r.pop()
print(np.array(r))

【讨论】:

    【解决方案2】:

    逐行解释计算

    import numpy as np                                                      
    
    condition = np.array([True, True, True, False, False, True, False, True, True, False, True])                       
    
    rvs = condition[::-1]   # Reverse the array order
    rvs                                                                     
    # array([ True, False,  True,  True, False,  True, False, False,  True,
            True,  True])
    
    cum_rvs = rvs.cumsum()  # Cumulative sum of Trues                                         
    cum_at_zero = (~rvs)*cum_rvs   # Cum where rvs is True set to zero                                         
    
    cum_max = np.maximum.accumulate( cum_at_zero ) # Equivalent to cummax( cum_at_zero )
    cum_max                                                               
    # array([0, 1, 1, 1, 3, 3, 4, 4, 4, 4, 4])
      
    result = cum_rvs - cum_max  # Use cum_max to adjust the cum_rvs down                        
    
    result = result[::-1]  # Reverse the result order                                                
    result                                                                  
    # array([3, 2, 1, 0, 0, 1, 0, 2, 1, 0, 1])
    

    或者更简洁的形式:

    rvs = condition[::-1]                                                   
    cum_rvs = rvs.cumsum()
    
    result = ( cum_rvs - np.maximum.accumulate((~rvs)*cum_rvs ))[::-1]   
                
    
                      
    

    【讨论】:

      【解决方案3】:
      import itertools
      condition = np.array([True, True, True, False, False, True, False, True, True, False, True])
      group_list = [list(g) for _, g in itertools.groupby(enumerate(condition), key = lambda x: x[-1])]
      temp = 0
      ans = []
      for item in group_list:
          if item[0][1]:
              for i in range(len(item)):
                  ans.append(len(item) - (item[i][0] - temp))
              temp += len(item)
          else:
              for i in range(len(item)):
                  ans.append(0)
              temp += len(item)
      print(ans)  
      >>> [3, 2, 1, 0, 0, 1, 0, 2, 1, 0, 1]      
      

      【讨论】:

        【解决方案4】:

        您实际上可以使用两行代码来全面完成此操作,而无需扩展库:

        false_indices = [np.where(condition[j:] == False)[0] for j in range(len(condition))]
        
        result = np.array([arr[0] if arr.size != 0 else int(condition[-1]) for arr in result])
        

        如果不是 conditions 中的最后一个 bool 会引发 IndexError,它甚至可能是单行代码。

        【讨论】:

          猜你喜欢
          • 2020-08-24
          • 1970-01-01
          • 2021-12-25
          • 2021-08-13
          • 1970-01-01
          • 2018-05-24
          • 2012-01-11
          • 2018-03-31
          • 2019-03-14
          相关资源
          最近更新 更多