One way would be to first unnest the dictionary and set the values as keys with their corresponding keys as values. And then you can use a list comprehension and map the values in each of the lists in the dataframe.
It'll be necessary to take a set
before returning a the result from the mapping in each iteration in order to avoid repeated values. Also note that or None
is doing the same as if x is not None else None
here, which will return None
in the case a list is empty. For a more detailed explanation on this you may check this post:
df = pd.DataFrame({'col1':[["Apple", "Banana"], ["Kiwi"], None, ["Apple"], ["Banana", "Kiwi"]]})
d = {1: ["Apple", "Banana"], 2: ["Kiwi"]}
d = {i:k for k, v in d.items() for i in v}
# {'Apple': 1, 'Banana': 1, 'Kiwi': 2}
out = [list(set(d[j] for j in i)) or None for i in df.col1.fillna('')]
# [[1], [2], None, [1], [1, 2]]
pd.DataFrame([out]).T
0
0 [1]
1 [2]
2 None
3 [1]
4 [1, 2]