Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas increment count column based on value of another column

Tags:

python

pandas

I have a df that is the result of a join:

   ID   count
0  A   30
1  A   30
2  B   5
3  C   44
4  C   44
5  C   44

I would like to be able to iterate the count column based on the ID column. Here is an example of the desired result:

   ID   count
0  A   30
1  A   31
2  B   5
3  C   44
4  C   45
5  C   46

I know there are non-pythonic ways to do this via loops, but I am wondering if there is a more intelligent (and time efficient, as this table is large) way to do this.

like image 489
wylie Avatar asked Oct 20 '25 18:10

wylie


1 Answers

Transform the group to get a cumulative count and add it to count, eg:

df['count'] += df.groupby('ID')['count'].cumcount()

Gives you:

  ID  count
0  A     30
1  A     31
2  B      5
3  C     44
4  C     45
5  C     46
like image 123
Jon Clements Avatar answered Oct 22 '25 08:10

Jon Clements