首页 > 解决方案 > 使用字典转换熊猫系列中列表的元素

问题描述

我有以下熊猫数据框:

1    ["Apple", "Banana"]
2    ["Kiwi"]
3    None
4    ["Apple"]
5    ["Banana", "Kiwi"]

和以下字典:

{1: ["Apple", "Banana"],
2: ["Kiwi"]}

我现在想使用字典映射我的数据框中列表中的所有条目。结果应如下所示:

1    [1]
2    [2]
3    None
4    [1]
5    [1, 2]

怎样才能最有效地做到这一点?

标签: pythonpandas

解决方案


方法1 我正在使用unnesting

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

方法二循环

[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}]

数据输入

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

推荐阅读