adding alternating values to a string with duplicate values

Viewed 93

I have a pandas dataframe, in the ID column the values are strings: 1,1,2,2,3,3,4,4,5,5, etc....

I would like to add to the string so it looks like 1.1,1.2,2.1,2.2,3.1,3.2, etc...

Ideally, if there is a third or fourth identical value then it is logically updated like 1.1, 1.2, 1.3, 1.4, etc...

How is this best achieved?

1 Answers

You'd have to use GroupBy.cumcount. Then use concatenate them using Series.str.cat.

# s = pd.Series(['1', '1', '2', '2', '3', '3', '4', '4', '5', '5'])
s.str.cat(s.groupby(s).cumcount().add(1).astype(str), sep='.')

# 0    1.1
# 1    1.2
# 2    2.1
# 3    2.2
# 4    3.1
# 5    3.2
# 6    4.1
# 7    4.2
# 8    5.1
# 9    5.2
# dtype: object

Related