【问题标题】:Pandas/Numpy How to generate a rolling count column?Pandas/Numpy 如何生成滚动计数列?
【发布时间】:2021-02-04 16:22:32
【问题描述】:

我有一个有两列的表。第二列是二进制,0 或 1 值。我想保持这些值的运行计数,直到它切换。例如,我想添加一个如下所示的“计数”列:

Date          sig   count
2000-01-03    0     1
2000-01-04    0     2
2000-01-05    1     1
2000-01-06    1     2
2000-01-07    1     3
2000-01-08    1     4
2000-01-09    0     1
2000-01-010   0     2
2000-01-011   0     3
2000-01-012   0     4
2000-01-013   0     5

有没有一种简单的方法可以使用 pandas、numpy 或简单的 python 来执行此操作而无需迭代或使用循环?

【问题讨论】:

    标签: python r pandas numpy dataframe


    【解决方案1】:
    df['count'] = df.groupby((df['sig'] != df['sig'].shift(1)).cumsum()).cumcount()+1
    
    In [1571]: df
    Out[1571]: 
               Date  sig  count
    0    2000-01-03    0      1
    1    2000-01-04    0      2
    2    2000-01-05    1      1
    3    2000-01-06    1      2
    4    2000-01-07    1      3
    5    2000-01-08    1      4
    6    2000-01-09    0      1
    7   2000-01-010    0      2
    8   2000-01-011    0      3
    9   2000-01-012    0      4
    10  2000-01-013    0      5
    

    【讨论】:

      【解决方案2】:

      numpy 中,您可以找到一个索引,其中不同的组开始和这些组的计数,然后将np.add.accumulate 应用于一系列重复的,其中一些被替换:

      def accumulative_count(sig):
          marker_idx = np.flatnonzero(np.diff(sig)) + 1
          counts = np.diff(marker_idx, prepend=0)
          counter = np.ones(len(sig), dtype=int)
          counter[marker_idx] -= counts
          return np.add.accumulate(counter)
      
      df['count'] = accumulative_count[df['sig']]
      

      示例运行:

      sig = [0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0]
      marker_idx = np.flatnonzero(np.diff(sig)) + 1
      counts = np.diff(marker_idx, prepend=0,)
      counter = np.ones(len(sig), dtype=int)
      counter[marker_idx] -= counts
      
      >>> marker_idx #starts of groups
      array([2, 6], dtype=int64)
      >>> counts #counts of groups
      array([2, 4], dtype=int64)
      >>> counter #a sequence of units with some of the units replaced
      array([ 1,  1, -1,  1,  1,  1, -3,  1,  1,  1,  1])
      >>> np.add.accumulate(counter) #output
      array([1, 2, 1, 2, 3, 4, 1, 2, 3, 4, 5], dtype=int32)
      

      【讨论】:

        猜你喜欢
        • 2022-01-18
        • 2019-01-03
        • 2020-05-09
        • 1970-01-01
        • 2018-02-07
        • 2022-11-25
        • 2021-12-08
        • 2019-10-27
        • 2022-07-26
        相关资源
        最近更新 更多