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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With