【问题标题】:pyspark - how to find sum of rows filtered [duplicate]pyspark - 如何找到过滤的行总和[重复]
【发布时间】:2022-01-07 12:44:59
【问题描述】:

我有一个包含两列的数据集:Country、Adclicks。如何找到广告点击次数最多的国家/地区?

Country | Ad Click
USA       1
USA       0
USA       1
PR        0
PR        0
PR        1

【问题讨论】:

  • 1) groupBy 国家 + sum 2) agg w/ max 点击次数

标签: apache-spark pyspark apache-spark-sql


【解决方案1】:

假设您的 DataFrame 如果定义为变量“df”,则如下所示:

import pyspark.sql.functions as psf

# Get aggregate sum
s = df.groupby("Country").agg({'Ad Click': 'sum'})

# Get and display top country
s.registerTempTable("sums_table")
query = """
    SELECT Country
    FROM sums_table
    WHERE `sum(Ad Click)` = (
        SELECT MAX(`sum(Ad Click)`)
        FROM sums_table)
"""
top_country = spark.sql(query).collect()
print(top_country[0]["Country"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2018-03-17
    • 2023-03-28
    相关资源
    最近更新 更多