Calculating the number of specific consecutive equal values in a vectorized way in pandas

后端 未结 1 1135
礼貌的吻别
礼貌的吻别 2020-12-05 08:42

Let\'s say we have the following pandas DataFrame:

In [1]:
import pandas as pd
import numpy as np

df = pd.DataFrame([0, 1, 0, 0, 1, 1, 0, 1, 1, 1], columns=         


        
相关标签:
1条回答
  • 2020-12-05 09:15

    You can do something like this(credit goes to: how to emulate itertools.groupby with a series/dataframe?):

    >>> df['in'].groupby((df['in'] != df['in'].shift()).cumsum()).cumsum()
    0    0
    1    1
    2    0
    3    0
    4    1
    5    2
    6    0
    7    1
    8    2
    9    3
    dtype: int64
    
    0 讨论(0)
提交回复
热议问题