【问题标题】:How to calculate numbers of "uninterrupted" repeats in an array in python?如何计算python数组中“不间断”重复的数量?
【发布时间】:2019-06-24 02:33:54
【问题描述】:

我有一个像这样的 0,1 numpy 数组:

 [0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0]

我想要一个函数告诉我数字1 在这个数组中分别重复3,2,4 次。有没有一个简单的 numpy 函数呢?

【问题讨论】:

  • 你正在寻找一个rle。周围有很多实现。
  • 重新打开,因为重复的不是同一个问题;随意关闭更好的副本。
  • 谢谢@Psidom!

标签: python numpy


【解决方案1】:

这是一种首先找到集群然后使用Counter 获取其频率的方法。第一部分的灵感来自this 二维数组的答案。我添加了第二个Counter 部分以获得所需的答案。

如果您发现链接的原始答案有帮助,请访问并投票。

from scipy.ndimage import measurements
from collections import Counter

arr = np.array([0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0])

cluster, freq = measurements.label(arr)

print (list(Counter(cluster).values())[1:])
# [3, 2, 4]

【讨论】:

    【解决方案2】:

    假设你只有 0 和 1:

    import numpy as np
    a = np.array([0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0])
    
    # pad a with 0 at both sides for edge cases when a starts or ends with 1
    d = np.diff(np.pad(a, pad_width=1, mode='constant'))
    # subtract indices when value changes from 0 to 1 from indices where value changes from 1 to 0
    np.flatnonzero(d == -1) - np.flatnonzero(d == 1)
    # array([3, 2, 4])
    

    【讨论】:

      【解决方案3】:

      自定义实现?

      def count_consecutives(predicate, iterable):
        tmp = []
        for e in iterable:
          if predicate(e): tmp.append(e)
          else:
            if len(tmp) > 0: yield(len(tmp)) # > 1 if you want at least two consecutive
            tmp = []
        if len(tmp) > 0: yield(len(tmp)) # > 1 if you want at least two consecutive
      

      所以你可以:

      array = [0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0,0]
      (count_consecutives(lambda x: x == 0, array)
      #=> [3, 2, 4]
      

      还有:

      array = [0,0,0,1,2,3,0,0,3,2,1,0,0,1,11,10,10,0,0,100]
      count_consecutives(lambda x: x > 1, array)
      # => [2, 2, 3, 1]
      

      【讨论】:

        猜你喜欢
        • 2017-01-08
        • 2016-05-25
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 1970-01-01
        • 2023-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多