我有以下数据框:
df1
Name Leads
0 City0 22
1 City1 11
2 City2 28
3 City3 15
4 City4 14
5 City5 15
6 City6 25
df2
Name Leads
0 City1 13
1 City2 0
2 City4 2
3 City6 5
我想仅当名称列中的值匹配时才对潜在客户列中的值求和。我试过:
df3 = df1['Leads'] + df2['Leads'].where(df1['Name']==df2['Name'])
返回错误:
ValueError: Can only compare identically-labeled Series objects
在 StackOverflow 上看过类似的问题,但没有一个适合我的特定用途。有人能指出我正确的方向吗?
最佳答案
假设 df2.Name
值是唯一的,并且 df2
有确切的 2 列作为您的示例。让我们使用 map
和 defaultdict
from collections import defaultdict
df1.Leads + df1.Name.map(defaultdict(int, df2.to_numpy()))
Out[38]:
0 22
1 24
2 28
3 15
4 16
5 15
6 30
dtype: int64
关于python - Pandas:如何有条件地对两个不同数据框中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63606731/