python - 使用字典转换熊猫系列中列表的元素
问题描述
我有以下熊猫数据框:
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]
怎样才能最有效地做到这一点?
解决方案
方法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"]}
推荐阅读
- typescript - Nuxt - asyncData 错误:“绑定元素 '$axios' 隐式具有 'any' 类型。”
- visual-studio-code - 如何使用 VS Code 为 Windows 做出本机反应?
- c++ - 首次尝试使用 CMake 编译 Open-CV 时出错
- reactjs - 我使用 fetchAPI 和 useState 收到此错误“TypeError:userData.map 不是函数”
- javascript - JavaScript 检查迭代器是否包含值
- c# - 如何将 html 内容从变量加载到 UWP WebView
- json - 包含管道字符的键的 JQ 提取错误
- r - 如何按不同组绘制数据?
- python - 基于唯一值将数据帧子集为小数据帧并同时写入 csv 文件的有效方法
- javascript - 在 JavaScript 中为同一节点列表中的每个按钮执行不同的命令