How can I get Pandas to add an incrementing suffix to a value based on occurrences

Viewed 149

I would like to add a prefix that inclemently counts number of occurrences of values in a column.

INPUT

1234567
1234568
1234567
1234565
1234567
1234567
1234568
1234565

OUTPUT

1234567#1
1234568#1
1234567#2
1234565#1
1234567#3
1234567#4
1234568#2
1234565#2

Thanks for your help!

1 Answers

You can generate the sequences with a groupby-cumcount and append:

df = pd.DataFrame({'A': [1234567, 1234568, 1234567, 1234565, 1234567, 1234567, 1234568, 1234565]})

df.A.astype(str) + '#' + df.groupby('A').cumcount().add(1).astype(str)

Output:

0    1234567#1
1    1234568#1
2    1234567#2
3    1234565#1
4    1234567#3
5    1234567#4
6    1234568#2
7    1234565#2
dtype: object
Related