babz
babz

Reputation: 479

Create a counter based on another field

I want to create the following table.

Desired Table

ID     Coverage   Count
1      A          1
1      A          2
1      A          3
1      B          1
2      C          1
2      A          1
2      A          2
2      C          2

I currently have just ID and coverage in a table and need to add the count column. I want it to, starting at 1, count +1 for the same Coverage under the same ID.

In SQL it would involve grouping by ID and Coverage but I'm not sure where to start this in python.

Upvotes: 1

Views: 58

Answers (1)

BENY
BENY

Reputation: 323226

You need cumcount here

df['Newcount']=df.groupby(['ID','Coverage']).cumcount()+1
df
Out[588]: 
   ID Coverage  Count  Newcount
0   1        A      1         1
1   1        A      2         2
2   1        A      3         3
3   1        B      1         1
4   2        C      1         1
5   2        A      1         1
6   2        A      2         2
7   2        C      2         2

Upvotes: 2

Related Questions