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

如何让pandas.compare()返回差异对应的另一行完整列数据?

获取DataFrame对比中差异行的完整other侧数据

现有两个DataFrame df_a 和 df_b,使用 df_a.compare(df_b) 只能得到差异列的self和other值,但需要获取与self存在差异的other侧完整行数据(包含所有列)。

示例代码及当前输出:

import pandas as pd

first = {
    'Name': ['Bob', 'Mike', 'Alex'],
    'Job': ['Forklift Operator', 'Forklift Operator', 'Master Forklift Operator']
}

second = {
    'Name': ['Bob', 'Mike', 'Allen'],
    'Job': ['Forklift Operator', 'Forklift Operator', 'Master Forklift Operator']
}

df_a = pd.DataFrame(first)
df_b = pd.DataFrame(second)

# 当前执行的对比代码
df_c = df_a.compare(df_b)
print(df_c)

当前输出:

Name
    self  other
2   Alex  Allen

期望输出(other侧的完整差异行):

Name                       Job
2  Allen  Master Forklift Operator

解决方案

利用compare方法返回结果的索引,直接从df_b中提取对应索引的行即可:

# 获取差异行的索引,提取df_b中对应行
result = df_b.loc[df_c.index]
print(result)

执行后输出:

Name                       Job
2  Allen  Master Forklift Operator

原理说明

df_a.compare(df_b)返回的结果中,索引就是两个DataFrame存在差异的行的位置。通过df_b.loc[差异索引]就能精准获取other侧(即df_b)的完整差异行数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:52:16