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

PySpark如何统计DataFrame两列中所有不同值的总数量

PySpark 两列全局去重计数实现方案

以下两种实现均为PySpark原生分布式方法,全程在集群侧执行,不会拉取全量数据到Driver端,符合大数据处理的设计逻辑:

方法1:列堆叠后全局去重计数

适合数据量中等、两列重复值不多的场景,写法最简洁:

from pyspark.sql.functions import explode, array

# 将id1、id2合并为数组后炸开为单列,去重后计数
distinct_total = df.select(explode(array("id1", "id2")).alias("all_id")) \
                   .distinct() \
                   .count()

如果需要排除空值统计,可在distinct()前添加过滤条件:.filter("all_id is not null")

方法2:单字段预去重后合并统计

适合两列基数大、重复值多的场景,先对单字段去重再合并,能大幅减少shuffle数据量,性能更优:

# 分别对两列去重,统一列名后合并
id1_unique = df.select("id1").distinct().withColumnRenamed("id1", "all_id")
id2_unique = df.select("id2").distinct().withColumnRenamed("id2", "all_id")

distinct_total = id1_unique.union(id2_unique) \
                           .distinct() \
                           .count()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 00:15:04