Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

python pandas how to edit value of duplicate in python ?

By M.K. Verma · 3 May 2022

python pandas how to edit value of duplicate in python ?

use groupby.cumcount to create groups; then you could use str.zfill to pad 0s and mask the first elements of each group:

groups = df.groupby('sku').cumcount()
df['new'] = df['sku'] + ('-' + groups.astype('string').str.zfill(2)).mask(groups.eq(0), '')

Output:

       sku         new
0  FAT-001     FAT-001
1  FAT-001  FAT-001-01
2  FAT-001  FAT-001-02
3  FAT-002     FAT-002
4  FAT-002  FAT-002-01