Count groups of consecutive 1s in pandas
问题 I have a list of '1's and '0s' and I would like to calculate the number of groups of consecutive '1's. mylist = [0,0,1,1,0,1,1,1,1,0,1,0] Doing it by hand gives us 3 groups but is there a way to do it by python? 回答1: Option 1 With pandas . First, initialise a dataframe: In [78]: df Out[78]: Col1 0 0 1 0 2 1 3 1 4 0 5 1 6 1 7 1 8 1 9 0 10 1 11 0 Now calculate sum total by number of groups: In [79]: df.sum() / df.diff().eq(1).cumsum().max() Out[79]: Col1 2.333333 dtype: float64 If you want just