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

Pandas groupby with each group treated as a unique group

Please assist. How do I get the cumsum of a pandas groupby, but my data is boolean 0 and 1. I want to treat each group of 0s or 1s as unique values, and the count to reset when new values are met.

I currently have this which sums up all 1s and 0’s

df['grp'] = df.groupby("dir")["dir"].cumsum())

My desired output

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

df  = pd.DataFrame({"dir":[1,1,1,1,0,0,0,1,1,1,1,0,0,0],
                  "grp": [1,2,3,4,1,2,3,1,2,3,4,1,2,3,]})

>Solution :

Use:

In [1495]: df['grp'] = df.groupby((df['dir'] != df['dir'].shift(1)).cumsum()).cumcount()+1

In [1496]: df
Out[1496]: 
    dir  grp
0     1    1
1     1    2
2     1    3
3     1    4
4     0    1
5     0    2
6     0    3
7     1    1
8     1    2
9     1    3
10    1    4
11    0    1
12    0    2
13    0    3
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