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

Merge two DataFrames based on a string aggregated column

I have the below DF that contains

Lookup Definition
A Apple
B Banana
C Carrot

I have another DF2:

SNo Lookup Values
1 ['A', 'B']
2 ['A', 'C']
3 ['B', 'C']

Note: "Lookup Values" column is a list of strings

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

What is the most simple way of performing the JOIN to get the below:

SNo Lookup Values Lookup Definitions
1 A, B Apple, Banana
2 A, C Apple, Carrot
3 B, C Banana, Carrot

>Solution :

Try explode, merge, then groupby:

(df2.explode('Lookup Values')
    .merge(df1, left_on='Lookup Values', right_on='Lookup', how='left')
    .groupby('SNo', as_index=False)
    .agg({'Lookup':','.join, 'Definition':','.join})
)

Output:

   SNo Lookup     Definition
0    1    A,B   Apple,Banana
1    2    B,C  Banana,Carrot
2    3    C,A   Carrot,Apple
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