python - 在 df2 列中以逗号分隔值合并 df1 列中的值的两个数据框
问题描述
输入:具有以下数据的两个数据框:df1:(注意 EmployeeID 是一串逗号分隔值)
| Employee Name | EmployeeID |
|---------------|------------|
| John | 2, 22 |
| Kim | 3 |
df2:
| EmployeeID | Hours |
|------------|-------|
| 2 | 8 |
| 3 | 10 |
我想在 df1.EmployeeID 的 ID 列表中合并 df2.EmployeeID 上的 df1 和 df2。
输出:
| Employee Name | EmployeeID | Hours |
|---------------|------------|-------|
| John | 2,22 | 8 |
| Kim | 3 | 10 |
解决方案
如果需要匹配多个值,例如在理解EmployeeID = 2,3,22
中Hours=8+10
使用字典映射split
和sum
:
#converted to strings for match splitted values
df2['EmployeeID'] = df2['EmployeeID'].astype(str)
d = df2.set_index('EmployeeID')['Hours'].to_dict()
f = lambda x: sum(d[y] for y in x.split(', ') if y in d)
df1['Hours'] = df1['EmployeeID'].apply(f)
print (df1)
Employee Name EmployeeID Hours
0 John 2, 22 8
1 Kim 3 10
整数匹配的另一个想法:
d = df2.set_index('EmployeeID')['Hours'].to_dict()
f = lambda x: sum(d[int(y)] for y in x.split(', ') if int(y) in d)
df1['Hours'] = df1['EmployeeID'].apply(f)
推荐阅读
- angular - 将rest api promise请求转换为角度离子中的rxjs请求
- reactjs - 如何删除之前在 React useEffect() 中创建的实例
- python-3.x - 使用 python 的语音助手显示循环错误
- python - 尝试运行暗网检测时无法打开文件 yolov3_custom_last.weights
- javascript - 附加到 Amcharts 中的工具提示
- r - 计算整体平均值,而不是平均值
- javascript - 单击重置按钮时,角度材料拖放重置为初始位置
- c# - 索引的 Asp.net core mvc 可选参数
- jestjs - JEST 更改测试用例的预格式化输出
- r - 计算样本量以进行 mcnemar 测试