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

Map Id's in one dataframe with the corresponding names in another dataframe

I have below 2 dataframes:

df_1:
|   | assign_to_id |
|   | ------------ |
| 0 | 1, 2         |
| 1 | 2            |
| 2 | 3,4,5        |

df_2:
|   | id          | name       |
|   | ------------| -----------|
| 0 | 1           | John       | 
| 1 | 2           | Adam       |
| 2 | 3           | Max        |
| 3 | 4           | Martha     |
| 4 | 5           | Robert     |

I want to map the Id’s in the df_1 to the names in df_2 by matching their id’s

final_df:
|   | assign_to_name    |
|   | ----------------- |
| 0 | John, Adam        |
| 1 | Adam              |
| 2 | Max,Martha,Robert |

I don’t know how to achieve this. Looking forward to some help.

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

>Solution :

Idea is mapping column splitted by , by dictionary and then join back by ,:

d = df_2.assign(id = df_2['id'].astype(str)).set_index('id')['name'].to_dict()
f = lambda x: ','.join(d[y] for y in x.split(',') if y in d)
df_1['assign_to_name'] = df_1['assign_to_id'].replace('\s+', '', regex=True).apply(f)
print (df_1)
  assign_to_id     assign_to_name
0         1, 2          John,Adam
1            2               Adam
2        3,4,5  Max,Martha,Robert
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