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 to cumcount in group for specific value?

I have a dataframe:

  id    value
0  a       w
1  a       l
2  a       l
3  a       w
4  a       w
5  a       w
6  a       l

when I do df.groupby("id").cumcount() it returns:

0  0       
1  1       
2  2       
3  3       
4  4       
5  5       
6  6

I want to count only those ones that equal w in column value and it must be in dataframe form:

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

0  0              
3  0       
4  1       
5  2       

How to do that with cumcount function?

>Solution :

Use:

res = df.groupby((df["value"] != df["value"].shift()).cumsum()).cumcount()
res = res[df["value"].eq("w")]
print(res)

Output

0    0
3    0
4    1
5    2
dtype: int64

As an alternative:

s = (df["value"] != df["value"].shift()).cumsum()
res = s.groupby(s).cumcount()
res = res[df["value"].eq("w")]
print(res)
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