Count appearances of a value until it changes to another value

前端 未结 6 1090
予麋鹿
予麋鹿 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:29

    You can keep track of where the changes in df['values'] occur, and groupby the changes and also df['values'] (to keep them as index) computing the size of each group

    changes = df['values'].diff().ne(0).cumsum()
    df.groupby([changes,'values']).size().reset_index(level=0, drop=True)
    
     values
    10    2
    23    2
    9     3
    10    4
    12    1
    dtype: int64
    

提交回复
热议问题