1

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.

Deep_9289
  • 13
  • 4

1 Answers1

0

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252