I have dataframe column with values in lists, want to add new column with filtered values from list if they are in other dataframe.
df:
df = pd.DataFrame({'a':[1,2,5,7,9],'b':[[10,1,'xxx'],[],[1,2,3],[5],[25,27]]})
**a**|**b**
:-----:|:-----:
1|[10, 1, 'xxx']
2|[]
5|[1, 2, 3]
7|[5]
9|[25, 27]
df2:
df2 = pd.DataFrame({'d':[324,21,4353,345,4535,23],'e':[5,1,23,25,25,'xxx']})
I need to add new column with filtered column b in df so that it contains lists with only elements which are in df2 column e.
Result:
**a**|**b**|**c**
:-----:|:-----:|:-----:
1|[10, 1, 'xxx']|[1,'xxx']
2|[]|[]
5|[1, 2, 3]|[1]
7|[5]|[5]
Speed is crucial, as there is a huge amount of records.
What I did for now:
- created a set of possible values
l = list(df2['e'].unique())
- Try to use
df.assignwith comprehensive lists, but it's not quite working and too slow.
df.assign(mapped=[[x for x in row if x in l] for row in df.b])
Appreciate any help.
UPD
In lists and df2 not always integer values, sometimes it's strings.