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

Python及PySpark中如何过滤两个DataFrame共有行保留df_today独有记录

实现方案

我们需要提取df_today中整行完全不存在于df_history的独有记录,两种运行环境的实现代码如下:


1. Python(Pandas)实现

方法1:左反连接实现(推荐,逻辑清晰性能稳定)

import pandas as pd

# 所有列作为匹配键,左连接同时标记来源
df_result = df_today.merge(
    df_history,
    how='left',
    on=df_today.columns.tolist(),
    indicator=True
)
# 筛选仅在df_today中存在的记录,删除标记列
df_result = df_result[df_result['_merge'] == 'left_only'].drop(columns='_merge')

方法2:drop_duplicates实现

# 给两个数据集加来源标记
df_history['source'] = 'history'
df_today['source'] = 'today'

# 合并后删除全字段重复的所有行
df_all = pd.concat([df_history, df_today], ignore_index=True)
df_result = df_all.drop_duplicates(keep=False, subset=df_all.columns.difference(['source']))

# 筛选仅属于df_today的记录,清理标记列
df_result = df_result[df_result['source'] == 'today'].drop(columns='source')

2. PySpark实现

方法1:差集运算(最简洁,自动整行匹配)

# subtract直接返回存在于df_today但不存在于df_history的记录
df_result = df_today.subtract(df_history)

方法2:左反连接实现(适合自定义匹配键的场景)

# 所有列作为匹配键
join_keys = df_today.columns
df_result = df_today.join(
    df_history,
    on=join_keys,
    how='left_anti'
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:06:06