python - 使用一个命令在 Spark 中进行不同和求和聚合

标签 python scala apache-spark pyspark apache-spark-sql

我正在做一些 Spark 训练,并且想知道如何优化我的一项任务。目标很简单:根据下表中的订单日期和状态计算不同的订单数量和订单总值(value):

Input table

这必须在 Spark 的 Dataframe API(Python 或 Scala)中完成,而不是 SQL。

在 SQL 中,这很简单:

select order_status, order_date, count(distinct order_item_id), sum(order_item_subtotal) 
from df 
group by order_status, order_date

我让它在 PySpark 中工作的唯一方法是三个步骤:

  1. 计算总订单

    df_to = df.groupby('order_date','order_status')\ .agg(countDistinct(df.order_id)\ .alias('total_orders'))

  2. 计算不同的订单商品 ID

    df_ta = df.groupby('order_date','order_status')\ .sum('order_item_subtotal')\ .alias('total_amount')\ .withColumnRenamed("sum(order_item_subtotal)","total_amount")

  3. 连接上面的表格

    dfout = df_to.join(df_ta, [df_to.order_date == df_ta.order_date, df_to.order_status == df_ta.order_status], 'inner').select(df_to.order_date, df_to.order_status, df_to .total_orders, df_ta.total_amount)

有更聪明的方法吗?预先感谢您!

最佳答案

agg 中,您可以在一个 groupby 中执行这两项计算,如下所示:

import pyspark.sql.functions as func

df_agg = df.groupby("order_date", "order_status").\
    agg(
        func.countDistinct("order_id").alias("total_orders"),
        func.sum("order_item_subtotal").alias("total_amount")
    )

关于python - 使用一个命令在 Spark 中进行不同和求和聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52412597/

相关文章:

scala - 通过鉴别器使用嵌套的 Coproduct 解码 Case 类

python - 在 Python 中按日期时间对缺少日期的用户列表进行排序

python - 在 python 中是否可以轻松切换出 GPU

scala - 用于带有错误累积的异步处理的函数签名

scala - 我期望 Scala 中的可变排序集不起作用(也许我错过了一些东西)

scala - 在scala中将列从一个数据帧添加到另一个数据帧

python - 是否可以在 Python 中创建动态本地化范围?

Python 如何创建可更新的图?

apache-spark - 使用 Spark 进行流式传输时查询数据库是一种好习惯吗

amazon-web-services - 如何从 shell 脚本中捕获 Spark 错误