Troy
Troy

Reputation: 35

Pandas: column counting ordered occurrence of value in different column

I need to apply logic depending on if a value in a column has occurred more than one time. I got what I needed by referencing this post. However, I was hoping to create a new column that looked like this:

Col1      Desired Column
Value1     1
Value1     2
Value2     1
Value1     3
Value2     2
Value3     1

Such that the 'Desired Column' is giving a count in consecutive order of the value's occurrence in Col1.

Appreciate the help!

Upvotes: 0

Views: 39

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34066

Like this:

In [1701]: df['Desired Column'] = df.groupby('Col1').cumcount() + 1                                                                                                                                         

In [1702]: df                                                                                                                                                                                               
Out[1702]: 
     Col1  Desired Column
0  Value1               1
1  Value1               2
2  Value2               1
3  Value1               3
4  Value2               2
5  Value3               1

Upvotes: 2

Related Questions