Convert elements of list in pandas series using a dict

dag*_*run 7 python pandas

I have the following Pandas dataframe:

1    ["Apple", "Banana"]
2    ["Kiwi"]
3    None
4    ["Apple"]
5    ["Banana", "Kiwi"]
Run Code Online (Sandbox Code Playgroud)

and the following dict:

{1: ["Apple", "Banana"],
2: ["Kiwi"]}
Run Code Online (Sandbox Code Playgroud)

I would now like to map all the entries in the lists in my dataframe using the dictionary. The result should be the following:

1    [1]
2    [2]
3    None
4    [1]
5    [1, 2]
Run Code Online (Sandbox Code Playgroud)

How can this be done most efficiently?

WeN*_*Ben 4

我正在使用的方法1unnesting

d={z :  x for x , y in d.items() for z in y }
s=unnesting(s.to_frame().dropna(),[0])[0]\
   .map(d).groupby(level=0).apply(set).reindex(s.index)
Out[260]: 
0       {1}
1       {2}
2       NaN
3       {1}
4    {1, 2}
Name: 0, dtype: object
Run Code Online (Sandbox Code Playgroud)

方法2循环

[set(d.get(y) for y in x) if  x is not None  else None for x in s ]
#s=[set(d.get(y) for y in x) if  x is not None  else None for x in s ]

Out[265]: [{1}, {2}, None, {1}, {1, 2}]
Run Code Online (Sandbox Code Playgroud)

数据输入

s=pd.Series([["Apple", "Banana"],["Kiwi"],None,["Apple"],["Banana", "Kiwi"]])
d={1: ["Apple", "Banana"],
2: ["Kiwi"]}
Run Code Online (Sandbox Code Playgroud)