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?
You can count the cumulative sum of a Boolean series indicating when your series equals a value:
df['id'] = df['type'].eq('a').cumsum()
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