Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count the number of times a condition consecutively exists across rows in a column in pandas

I have a simple df like this:

    data
0    0
1    0
2    1
3    1
4    0
5    0
6    1
7    1
8    1
9    1

I am interested in counting the number of times 1 consecutively occurs, and then creating a column assigning that value to each row in the chunk. It should look like this:

    data   count
0    0       0
1    0       0
2    1       2
3    1       2
4    0       0
5    0       0
6    1       4
7    1       4
8    1       4
9    1       4

Is there a simple pandas way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use np.where, cumsum

s=df.groupby((df['data']!=df['data'].shift(1)).cumsum()).transform('count')
df['count']=np.where(df['data'].eq(1),s['data'],0)



    data  count
0     0      0
1     0      0
2     1      2
3     1      2
4     0      0
5     0      0
6     1      4
7     1      4
8     1      4
9     1      4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading