如何找出PySpark DataFrame的Country列中不存在于参考DataFrame的值?
在PySpark中找出DataFrame中不存在于参考表的国家列表
针对大规模数据集,最高效的方式是使用左反连接(Left Anti Join),避免将大量数据加载到Driver端导致性能问题。
核心代码实现
from pyspark.sql.functions import col # 执行左反连接,筛选df_2中Country不在df_1中的记录 diff_df = df_2.join(df_1, on="Country", how="left_anti") # 提取Country列并转为列表 result = diff_df.select("Country").rdd.flatMap(lambda row: row).collect() print(result)
运行结果
['China', 'United States', 'italy']
关键说明
- 左反连接是Spark原生优化的分布式操作,仅保留左表(df_2)中无法与右表(df_1)匹配的行,匹配逻辑为Country列完全相等(区分大小写)。
- 相比
isin()方法(需将参考表所有Country值收集到Driver内存),左反连接更适合处理大规模数据集,避免内存溢出风险。
可选:忽略大小写的匹配
如果需要不区分大小写对比国家名称,可先统一转换为小写后再执行连接:
# 统一转换为小写进行匹配 diff_df_case_insensitive = df_2.join( df_1.withColumn("ref_country_lower", col("Country").lower()), col("Country").lower() == col("ref_country_lower"), how="left_anti" ) result_case_insensitive = diff_df_case_insensitive.select("Country").rdd.flatMap(lambda row: row).collect() print(result_case_insensitive)
运行结果
['China', 'United States']
内容的提问来源于stack exchange,提问作者Mohammad
相关产品推荐
相关产品推荐

