Count appearances of a value until it changes to another value

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

    The function groupby in itertools can help you, for str:

    >>> string = 'aabbaacc'
    >>> for char, freq in groupby('aabbaacc'):
    >>>     print(char, len(list(freq)), sep=':', end='\n')
    [out]:
        a:2
        b:2
        a:2
        c:2
    

    This function also works for list:

    >>> df = pd.DataFrame([10, 10, 23, 23, 9, 9, 9, 10, 10, 10, 10, 12], columns=['values'])
    >>> for char, freq in groupby(df['values'].tolist()):
    >>>     print(char, len(list(freq)), sep=':', end='\n')
    [out]:
        10:2
        23:2
         9:3
        10:4
        12:1
    

    Note: for df, you always use this way like df['values'] to take 'values' column, because DataFrame have a attribute values

提交回复
热议问题