I have a pandas df
| A | B |
|---|---|
| 1 | Asd |
| 1 | Thy |
| 1 | fhj |
| 2 | khh |
| 2 | ytr |
| 3 | hgj |
I want to have a counter column c based on the grouped values of A. Expected Output:
| A | B | C |
|---|---|---|
| 1 | Asd | 1 |
| 1 | Thy | 2 |
| 1 | fhj | 3 |
| 2 | khh | 1 |
| 2 | ytr | 2 |
| 3 | hgj | 1 |
Sample output provided
CodePudding user response:
You can use .groupby .cumcount:
df["C"] = df.groupby("A").cumcount() 1
print(df)
Prints:
A B C
0 1 Asd 1
1 1 Thy 2
2 1 fhj 3
3 2 khh 1
4 2 ytr 2
5 3 hgj 1
