Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add serial count to each group pandas python

Tags:

python

pandas

I have a simple problem but haven't been able to fix it.

I have a simple table such as:

group1 
a
a
a
b
b
b
c
c

I can add a count to the column with:

df['count'] = range(1, len(df) + 1)

I have tried to alter this with groupby functions but can't manage to stop the count and restart per group such as:

group1 count
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
like image 333
DGraham Avatar asked Feb 03 '26 16:02

DGraham


1 Answers

You could use cumcount. If you want to start from 1 you could add it:

In [16]: df['count'] = df.groupby('group1').cumcount()+1

In [17]: df
Out[17]:
  group1  count
0      a      1
1      a      2
2      a      3
3      b      1
4      b      2
5      b      3
6      c      1
7      c      2
like image 197
Anton Protopopov Avatar answered Feb 05 '26 05:02

Anton Protopopov