Home > OS >  Generate instance in column with duplicates in pandas
Generate instance in column with duplicates in pandas

Time:12-28

Input:

df_1 = pd.DataFrame({'A': ['a','a','b','a','b','c']})

    A
0   a
1   a
2   b
3   a
4   b
5   c

Expected Output:

     A
0   a.1
1   a.2
2   b.1
3   a.3
4   b.2
5   c.1

Need generate instance for duplicates in the column

CodePudding user response:

Use GroupBy.cumcount for counter with add 1 and converting to strings:

df_1['A'] = df_1['A']   '.'   df_1.groupby('A').cumcount().add(1).astype(str)

Or use Series.str.cat:

df_1['A'] = df_1['A'].str.cat(df_1.groupby('A').cumcount().add(1).astype(str), sep='.')

print (df_1)
     A
0  a.1
1  a.2
2  b.1
3  a.3
4  b.2
5  c.1

CodePudding user response:

df_1['A']=df_1['A'] '.' (df_1.groupby('A').cumcount() 1).astype(str)



    A
0  a.1
1  a.2
2  b.1
3  a.3
4  b.2
5  c.1
  • Related