How can I find number of GROUP of consecutive 1s in a binary number

Viewed 192

I have a pandas DataFrame that contains 1s and 0s in its rows. I want to count the number of group of consecutive 1s in my DataFrame. I repeat I am not asking for number of consecutive 1s, there are lots of examples on the web about it.

To be more exact:

Lets say the row of my pd.DataFrame is:

index value
0  0
1  1
2  1
3  0
4  0
5  1
6  0
7  1
8  0
9  1

I want output to be 4

3 Answers

try:

Only works when you don't have 1 at the begiining or the end.

df['value'].diff().eq(1).sum()

add 0 on top and the bottom of the series:

pd.concat([pd.Series([0]), df.value, pd.Series([0])]).diff().eq(1).sum()

4

Convert the value into list , and then do the following: This is from the top of my head you can probably find more efficient ways to do it

Countconsecutiveone=0
i=0
prv_is_one=0
While i<len(Newlist):
 if Newlist[i]==1 and prv_is_one==0:
       Countconsecutiveone+=1
       prv_is_one=1
 elif Newlist[i]==0 and prv_is_one==1:
           prv_is_one=0
 i+=1

Maybe you could use itertools.groupby:

>>> import pandas as pd
>>> from itertools import groupby
>>> d = {'value': [0, 1, 1, 0, 0, 1, 0, 1, 0, 1]}
>>> df = pd.DataFrame(data=d)
>>> df
   value
0      0
1      1
2      1
3      0
4      0
5      1
6      0
7      1
8      0
9      1
>>> sum(k for k, _ in groupby(df['value'])) 
4

Alternatively, if the key can be something other than 0/1 or you want to be more explicit:

>>> sum(1 for k, _ in groupby(df['value']) if k == 1)
4
Related