Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding alternating values to a string with duplicate values

Tags:

python

pandas

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?

like image 372
Spatial Digger Avatar asked Sep 29 '26 16:09

Spatial Digger


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

like image 164
Ch3steR Avatar answered Oct 01 '26 04:10

Ch3steR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!