Ad

Assign Count To Unique Values In In Another Column By Group Values In Another Column

- 1 answer

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

Ad

Answer

Use groupby and cumcount:

df['rank'] = df.groupby('Group')['People'].cumcount()+1
Ad
source: stackoverflow.com
Ad