0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.