3

I have a dataframe that contains a column that look like this

Name 
A
A
B
B
C

I want to append a column to this dataframe where it contains the occurrence number of the item in Name

Name  New_Column
A     1
A     2
B     1
B     2
C     1

So far, I can just turn Name column into a list, then loop over it and create the new_column, but is there a more straightforward way to do this directly in pandas?

Jason
  • 75
  • 9

1 Answers1

4

groupby and cumcount

cumcounts sole purpose is to increment each group separately. If you add one to the result and assign it as a new column:

df.assign(New_Column=df.groupby('Name').cumcount() + 1)

  Name  New_Column
0    A           1
1    A           2
2    B           1
3    B           2
4    C           1
piRSquared
  • 285,575
  • 57
  • 475
  • 624