【问题标题】:Grouping the same value based on a column increment using Python pandas使用 Python pandas 根据列增量对相同的值进行分组
【发布时间】:2022-01-22 13:46:58
【问题描述】:

我正在尝试做的是在某个时间段内使用 python 数据框对 0 的值进行分组,例如我有:

| Time (seconds) | Value |
|       1        |   0   |
|       2        |   0   |
|       3        |   0   |
|       4        |   1   |
|       5        |   0   |
|       6        |   1   |
|       7        |   1   |
|       8        |   0   |
|       9        |   0   |
|       10       |   0   |
|       11       |   1   |
|       12       |   0   |
|       13       |   0   |

我期望的输出是:

| Time (seconds) | Value | Group |
|       1        |   0   |   1   |
|       2        |   0   |   1   |
|       3        |   0   |   1   |
|       4        |   1   |       |
|       5        |   0   |   2   |
|       6        |   1   |       |
|       7        |   1   |       |
|       8        |   0   |   3   |
|       9        |   0   |   3   |
|       10       |   0   |   3   |
|       11       |   1   |       |
|       12       |   0   |   4   |
|       13       |   0   |   4   |

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    这里有一个使用numpy.split 的奇怪解决方案:

    arr = df['Value'].to_numpy()
    counter = 1
    out = []
    for ar in np.split(arr, np.where(arr==1)[0]):
        mask = ar==0
        out.append(np.where(mask, counter, 0))
        if mask.any():
            counter += 1
    df['Group'] = np.concatenate(out)
    

    输出:

        Time  Value  Group
    0      1      0      1
    1      2      0      1
    2      3      0      1
    3      4      1      0
    4      5      0      2
    5      6      1      0
    6      7      1      0
    7      8      0      3
    8      9      0      3
    9     10      0      3
    10    11      1      0
    11    12      0      4
    12    13      0      4I’m 
    

    【讨论】:

      【解决方案2】:

      您可以使用shiftcumsum 和掩码检查值何时发生变化:

      s = df['value'].eq(0)
      df['group'] = (s&s.ne(s.shift())).cumsum().where(s, 0)
      

      输出:

          time  value  group
      0      1      0      1
      1      2      0      1
      2      3      0      1
      3      4      1      0
      4      5      0      2
      5      6      1      0
      6      7      1      0
      7      8      0      3
      8      9      0      3
      9     10      0      3
      10    11      1      0
      11    12      0      4
      12    13      0      4
      

      【讨论】:

        【解决方案3】:

        你可以试试cumsum然后传给factorize

        s = df.Value.ne(0)
        
        df.loc[df.index[~s],'new'] = s.cumsum()[~s].factorize()[0]+1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-11-28
          • 1970-01-01
          • 1970-01-01
          • 2017-10-09
          • 1970-01-01
          • 2016-10-08
          相关资源
          最近更新 更多