'Get list and merge it with another located in a dataframe
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.
Solution 1:[1]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |