Count appearances of a value until it changes to another value

前端 未结 6 1086
予麋鹿
予麋鹿 2020-12-17 21:17

I have the following DataFrame:

df = pd.DataFrame([10, 10, 23, 23, 9, 9, 9, 10, 10, 10, 10, 12], columns=[\'values\'])

I want to calculate

6条回答
  •  自闭症患者
    2020-12-17 21:41

    itertools.groupby

    from itertools import groupby
    
    pd.Series(*zip(*[[len([*v]), k] for k, v in groupby(df['values'])]))
    
    10    2
    23    2
    9     3
    10    4
    12    1
    dtype: int64
    

    It's a generator

    def f(x):
      count = 1
      for this, that in zip(x, x[1:]):
        if this == that:
          count += 1
        else:
          yield count, this
          count = 1
      yield count, [*x][-1]
    
    pd.Series(*zip(*f(df['values'])))
    
    10    2
    23    2
    9     3
    10    4
    12    1
    dtype: int64
    

提交回复
热议问题