python - Pandas:如何有条件地对两个不同数据框中的值求和

标签 python pandas

我有以下数据框:

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 列作为您的示例。让我们使用 mapdefaultdict

来尝试一些不同的东西
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/

相关文章:

python - 重复列值以适合列名称数组

python - 基于 pandas 中的 groupby() 从多列计算

Python:尝试发送大文件时, 'MultipartEncoder' 对象不可迭代

python - 关闭 ipython 中所有打开的文件

python - 在树莓派上使用带有线程的 picamera 函数 start_recording

python - 在列中字典内的值上删除数据框上的重复项

python - PyCharm 中未显示数据帧头

python-3.x - 如何计算连续超过 1 个字符的大写单词的数量

python - 谷歌计算引擎示例

java - Android Socket 无法连接到笔记本电脑服务器 - 但本地 Java 程序可以