简体   繁体   中英

pandas increment count column based on value of another column

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM