Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas : Conditional rolling count

Here is my input dataframe:

type
a   
a   
a   
a   
a   
b   
b   
a   
a   
a

This is my expected output:

type,   id
a   ,   1
a   ,   2
a   ,   3
a   ,   4
a   ,   5
b   ,   5
b   ,   5
a   ,   6
a   ,   7
a   ,   8

I need to generate ID column based on 'type' column. I have two types 'a' & 'b'.. as long as it is 'a' I want to increment ID. If 'b', keep previous 'a' ID. How can I do this in a Pandas dataframe?

like image 509
JackJack Avatar asked Nov 20 '25 10:11

JackJack


1 Answers

You can count the cumulative sum of a Boolean series indicating when your series equals a value:

df['id'] = df['type'].eq('a').cumsum()
like image 97
jpp Avatar answered Nov 22 '25 00:11

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!