Newbie
Newbie

Reputation: 121

Pandas DataFrame column with increasing counter by values in another column

I have a data frame with a column having various letters ordered.

I want to create a column that counts increasingly the number of times a letter is repeated at each new row:

Letters     Counter
A           1
A           2
A           3
B           1
C           1
C           2
D           1
D           2
D           3
D           4

Is there a way to avoid a loop?

Upvotes: 0

Views: 285

Answers (1)

BENY
BENY

Reputation: 323226

We have cumcount

df['count']=df.groupby('Letters').cumcount()+1
df
  Letters  Counter  count
0       A        1      1
1       A        2      2
2       A        3      3
3       B        1      1
4       C        1      1
5       C        2      2
6       D        1      1
7       D        2      2
8       D        3      3
9       D        4      4

Upvotes: 1

Related Questions