Home > Net >  Pandas - groupby and transform to group number
Pandas - groupby and transform to group number

Time:04-28

Assuming I have this df:

    group1  group2
0    0       0
1    1       0
2    0       1
3    0       1
4    0       0

What I need is to simply groupby "group1" and "group2" columns -and create a new column ("new_group") with simply the ordinal number of the groupby. So the result should be:

    group1  group2   new_group
0    0       0         0
1    1       0         1
2    0       1         2
3    0       1         2
4    0       0         0

I tried using transform - but I didn't find the exact syntax I should use.

CodePudding user response:

Try with ngroup:

df['new_group'] = df.groupby(['group1', 'group2']).ngroup()
  • Related