首页 > 解决方案 > 在 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    |

标签: pythonpandasdataframemerge

解决方案


如果需要匹配多个值,例如在理解EmployeeID = 2,3,22Hours=8+10使用字典映射splitsum

#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)

推荐阅读