Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the latest same values from column python

Tags:

python

pandas

i have data like this:

   id   a   b   c   d
    1   y   y   z   z
    2   y   z   y   y
    3   y   y   y   y

i want to count value "y" from column a b c d from the last it change like this:

id    count_y
1     2
2     1
3     4

could you please help me with this?

like image 433
kj14 Avatar asked Dec 13 '22 08:12

kj14


2 Answers

You can do cumprod after set_index

s = df.set_index('id').eq('y').cumprod(axis = 1).sum(axis = 1)
s = s.reset_index(name='count_y')
s
Out[33]: 
   id  count_y
0   1        2
1   2        1
2   3        4
like image 88
BENY Avatar answered Dec 28 '22 01:12

BENY


As explanation in your comment, I think you may try this

df.set_index('id').eq('y').cummin(1).sum(1)

Out[11]:
id
1    2
2    1
3    4
dtype: int64
like image 26
Andy L. Avatar answered Dec 28 '22 03:12

Andy L.