I have a list of dictionaries like the following
dict = [{'id': 123, 'slot': 4}, {'id': 435, 'slot': 4}, {'id': 435, 'slot': 5}]
and a dataframe like
list_of_old_ids slot
[121,432] 4
[222,674] 5
and I would like to get the ids of the dict in a list and then merge that list with the one of the dataframe to get the following
list_of_new_ids slot
[121,432,123,435] 4
[222,674,435] 5
How can I do it? I've tried with str(list(map(itemgetter('id'), dict))) but then I cannot merge it with the dataframe column. Many thanks.
CodePudding user response:
df['list_of_new_ids'] = df.apply(lambda x: x['list_of_old_ids'] [z['id'] for z in [y for y in dict if y['slot'] == x['slot']]], axis = 1)
CodePudding user response:
Try this, which should be pretty fast:
new_df = pd.concat([df.explode('list_of_old_ids').rename({'list_of_old_ids':'id'},axis=1), pd.DataFrame(dict)]).groupby('slot').agg(list).reset_index()
Output:
>>> new_df
slot id
0 4 [121, 432, 123, 435]
1 5 [222, 674, 435]
