Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional replacement of row's values in pandas DataFrame

This is my pandas DataFrame:

ID  START   END  SEQ
1   11      12   5
1   14      15   6 
1   13      14   7 
2   10      14   1
3   11      15   1
3   16      17   2

I want to change the values of SEQ so that for the same ID the SEQ values would be 1, 2,... etc., e.g.

ID  START   END  SEQ
1   11      12   1
1   14      15   3 
1   13      14   2 
2   10      14   1
3   11      15   1
3   16      17   2

How can I do it efficiently avoiding for loop?

like image 227
duckertito Avatar asked Jan 17 '26 04:01

duckertito


1 Answers

Use cumcount on a groupby operation:

df.groupby('ID').cumcount()+1
like image 180
Zeugma Avatar answered Jan 19 '26 19:01

Zeugma



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!