Assign count to unique values in in another column by group values in another column

Viewed 44

I have a dataframe that is like this

Group | People
--------------
1       Cindy
1       Dylan
2       Kathy
3       Steven
3       Jonathan
3       Tiffany

And I want to add a new column that adds the count number, like this

Group | People     | Rank
--------------------------
1       Cindy        1
1       Dylan        2
2       Kathy        1
3       Steven       1
3       Jonathan     2
3       Tiffany      3

Essentially I want it to assign the count of unique individuals in a loop based on grouping by the Group

I know that df.groupby('Group')['People'].nunique() will get me the count, but want that in a loop

1 Answers

Use groupby and cumcount:

df['rank'] = df.groupby('Group')['People'].cumcount()+1
Related