Count appearances of a value until it changes to another value

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

    Using crosstab

    df['key']=df['values'].diff().ne(0).cumsum()
    pd.crosstab(df['key'],df['values'])
    Out[353]: 
    values  9   10  12  23
    key                   
    1        0   2   0   0
    2        0   0   0   2
    3        3   0   0   0
    4        0   4   0   0
    5        0   0   1   0
    

    Slightly modify the result above

    pd.crosstab(df['key'],df['values']).stack().loc[lambda x:x.ne(0)]
    Out[355]: 
    key  values
    1    10        2
    2    23        2
    3    9         3
    4    10        4
    5    12        1
    dtype: int64
    

    Base on python groupby

    from itertools import groupby
    
    [ (k,len(list(g))) for k,g in groupby(df['values'].tolist())]
    Out[366]: [(10, 2), (23, 2), (9, 3), (10, 4), (12, 1)]
    

提交回复
热议问题