Home > Enterprise >  How to generate unique code from occurrence in pandas
How to generate unique code from occurrence in pandas

Time:04-18

Here's my pandas dataframe

Id Code
1  A_01
2  C_03
3  A_01
4  C_02
5  C_03

My Expected Output

Id Code     Unique Code
1  A_01       A_01_0001
2  C_03       C_03_0001
3  A_01       A_01_0002
4  C_02       C_02_0001
5  C_03       C_03_0002

CodePudding user response:

With cumcount and zfill

df['unique_code'] = df['Code']   '_'   df.groupby('Code').cumcount().add(1).astype(str).str.zfill(4)
df
Out[386]: 
   Id  Code unique_code
0   1  A_01   A_01_0001
1   2  C_03   C_03_0001
2   3  A_01   A_01_0002
3   4  C_02   C_02_0001
4   5  C_03   C_03_0002
  • Related