1

I am trying to add a new column to my dataframe with the "index" or "order of appearance" of a row within a group.

For example, I have something like this

  col1  
0 John 
1 Lucy 
2 Jane 
3 Jane 
4 Jane 
5 Lucy 

I want to groupby('col1') and get the order of appearance within each group.

And I am trying to get something like this

  col1  col2                
0 John 1
1 Lucy 1
2 Jane 1
3 Jane 2
4 Jane 3
5 Lucy 2

I hope I was clear. A priori it doesn't seem too tricky to me, but I just can't do it!

Thanks!

1 Answers1

2
df['count'] = df.groupby(by=['col1']).cumcount()+1
print(df)

    col1  count
0  John       1
1  Lucy       1
2  Jane       1
3  Jane       2
4  Jane       3
5  Lucy       2
NYC Coder
  • 7,424
  • 2
  • 11
  • 24