You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas合并两个dataframe并生成差值列的实现方法

import pandas as pd

# 外连接两个DataFrame,按索引匹配,缺失值填充为0
result = pd.merge(df1, df2, left_index=True, right_index=True, how='outer').fillna(0)
# 计算diff列:count1减去count2
result['diff'] = result['count1'] - result['count2']
# 转换数值为整数类型,消除fillna带来的float格式问题
result = result.astype({"count1": int, "count2": int, "diff": int})

# 打印验证结果
print(result)

运行后输出结果完全符合预期:

count1  count2  diff
A          1       0     1
B          1       2    -1
C          1       2    -1
D          0       2    -2

内容的提问来源于stack exchange,提问作者QSBK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 18:42:02