Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concatenating two fields which have multiple values separated by delimiter using pandas

I have source csv file with structure as:

Col1, Col2, Col3, Col4
123, John, ID1|ID2|ID3, Lisbon|Kite|Dam
456, Tree, ID4|ID9|ID10|ID11, Chart||Cam|Dare
543, Jam, ID12, Jar

I need to concatenate the col3 and col4 values by maintaining the sequence and order of pipe(delimiter). The CombinedCol should also be a pipe separated column like below:

Col1, Col2, CombinedCol
123, John, ID1:Lisbon|ID2:Kite|ID3:Dam
456, Tree, ID4:Chart|ID9|ID10:Cam|ID11:Dare
543, Jam, ID12:Jar

I am trying this using pandas but I am stuck and not able to iterate the field values at the column

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df['CombinedCol']=df['Col3'].str.split('|')+':'+df['Col4'].str.split('|')

>Solution :

Use list comparehension with double zip – by splitted values by |, then zip and join by : and last join by | to new column:

zipped = zip(df['Col3'], df['Col4'])

df['CombinedCol'] = ['|'.join(':'.join(y).rstrip(':') 
                      for y in zip(a.split('|'), b.split('|'))) 
                      for a, b in zipped]
print (df)
   Col1  Col2               Col3             Col4  \
0   123  John        ID1|ID2|ID3  Lisbon|Kite|Dam   
1   456  Tree  ID4|ID9|ID10|ID11  Chart||Cam|Dare   
2   543   Jam               ID12              Jar   

                        CombinedCol  
0       ID1:Lisbon|ID2:Kite|ID3:Dam  
1  ID4:Chart|ID9|ID10:Cam|ID11:Dare  
2                          ID12:Jar 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading