Reputation: 155
Using Python, I have a panda dataframe
A B
1 red
2 blue
3 green
4 red
5 green
6 orange
7 red
I would like to create a column with an incremental counter based on the values in B. That is to resolve to
A B C
1 red 1
2 blue 1
3 green 1
4 red 2
5 green 2
6 orange 1
7 red 3
Upvotes: 2
Views: 1242
Reputation: 62037
Groupby each color and then use the cumcount
method.
df['C'] = df.groupby('B').cumcount() + 1
A B C
0 1 red 1
1 2 blue 1
2 3 green 1
3 4 red 2
4 5 green 2
5 6 orange 1
6 7 red 3
Upvotes: 4