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

如何在PySpark DataFrame中统计两列机场值的总出现次数

统计PySpark DataFrame中机场总出现次数的解决方案

方法一:合并已有的两个统计结果

如果你已经分别算出了出发地和目的地的统计DataFrame,可以通过关联+求和的方式得到总次数:

假设你已经得到两个统计结果的DataFrame:

  • origin_counts:包含Origin(机场名)和count_origin(出发地出现次数)两列
  • dest_counts:包含Destination(机场名)和count_dest(目的地出现次数)两列

执行以下代码:

from pyspark.sql.functions import coalesce, col

# 用外连接关联两个统计结果,保证所有机场都被包含
total_counts = origin_counts.alias("o").join(
    dest_counts.alias("d"),
    col("o.Origin") == col("d.Destination"),
    how="outer"
).select(
    # 取非空的机场名作为统一的Airport列
    coalesce(col("o.Origin"), col("d.Destination")).alias("Airport"),
    # 把null的次数视为0,相加得到总次数
    (coalesce(col("o.count_origin"), 0) + coalesce(col("d.count_dest"), 0)).alias("Count")
)

# 查看结果
total_counts.show()

方法二:直接从原始DataFrame一步统计(更高效)

其实不需要分开统计两列,直接把出发地和目的地列合并成一列,再分组计数,步骤更简洁:

from pyspark.sql.functions import explode, array

# 将Origin和Destination列合并为数组,再展开成单个Airport列
unpivoted_df = df.select(explode(array(col("Origin"), col("Destination"))).alias("Airport"))

# 分组统计每个机场的总次数
total_counts = unpivoted_df.groupBy("Airport").count().orderBy(col("Count").desc())

# 查看结果
total_counts.show()

运行后就能得到你期望的结果:

AirportCount
LHR3
LAX2
ATL2
JFK2
DFW1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:52:08