Arun Karthick
Arun Karthick

Reputation: 336

Combine 2 columns base on series

I have a dataset like this

A        B
1        100
2,3      100,200
4,5,6    100,200,300
7        100

I want to combine these two columns like this

A        B             C
1        100           1(100)
2,3      100,200       2(100),3(200)
4,5,6    100,200,300   4(100),5(200),6(300)
7        100           7(100)

Upvotes: 0

Views: 36

Answers (1)

jezrael
jezrael

Reputation: 862681

You can split each column by ,, zip and change format with f-strings:

df['C'] = [','.join(f'{y}({z})' for y, z in zip(a.split(','), b.split(','))) 
                                for a, b in zip(df.A, df.B)]
print (df)
       A            B                     C
0      1          100                1(100)
1    2,3      100,200         2(100),3(200)
2  4,5,6  100,200,300  4(100),5(200),6(300)
3      7          100                7(100)

Upvotes: 3

Related Questions