Python 将df1列中值的两个数据帧合并为df2列中逗号分隔的值

Python 将df1列中值的两个数据帧合并为df2列中逗号分隔的值,python,pandas,dataframe,merge,Python,Pandas,Dataframe,Merge,输入:包含以下数据的两个数据帧: df1:(注意EmployeeID是由逗号分隔的值组成的字符串) df2: 我想在df1.EmployeeID中的ID列表中合并df2.EmployeeID上的df1和df2 输出: | Employee Name | EmployeeID | Hours | |---------------|------------|-------| | John | 2,22 | 8 | | Kim | 3

输入:包含以下数据的两个数据帧: df1:(注意EmployeeID是由逗号分隔的值组成的字符串)

df2:

我想在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)

如果
EmployeeID
2,3,22
,则
Hours
8,10
?否,为8+10
#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)