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
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
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