1

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

tkxgoogle
  • 407
  • 4
  • 11

1 Answers1

2

Use groupby and cumcount:

df['rank'] = df.groupby('Group')['People'].cumcount()+1
wwnde
  • 26,119
  • 6
  • 18
  • 32