python - 通过字典解析并更新数据框中的空白
问题描述
请查看以下数据框:
A B
0 Fruit Apple
1 Car BMW
2 Cat
字典:{'Apple': 'Fruit', 'BMW':'Car','Cat': 'Animal'}
期望的输出:
A B
0 Fruit Apple
1 Car BMW
2 Animal Cat
我的想法:
- 解析 A 列
- 识别空白值
- 对于每个空白值,查看“B”列中对应的行元素(例如:“”->“猫”)
- 从该行获取值并用作标记为“字典”的已定义字典的键
- 使用键值对的输出值,并将空白值替换为字典的输出值
如果有人可以帮我在 python 中编写这个代码,那就太好了:)
解决方案
如果你的 DataFrame 和字典被命名为df
and d
,试试这个:
# Map column B to values of the dictionary
mapper = df['B'].map(d)
# Replace empty strings in A with corresponding dict-mapped value
df['A'] = df['A'].replace('', np.nan).fillna(mapper)
df
A B
0 Fruit Apple
1 Car BMW
2 Animal Cat
推荐阅读
- c - 有序列表搜索算法的输出不正确
- python-3.x - 使用 numpy 在矩阵中设置交替的非对角线元素
- javascript - 数据确认应包括检查的无线电输入的名称或值
- python - 我的代码中出现 Python“回溯错误”,不确定如何解决
- python - 使用 os.listdir(path) 循环时如何跳过前几个文件?
- datetime - 如何查找一个月内登录N次以上的客户?
- java - Intellij Executable Jar - 没有主清单属性与无法找到或加载主类
- python - Python中非线性二阶ODE的Rk4积分器
- android - android studio 中的未知错误。(资源)
- azure-data-explorer - Kusto 查询 - 按扩展列排序