pyspark-groupby category并对计数求和

blpfk2vs  于 2021-07-13  发布在  Spark
关注(0)|答案(2)|浏览(337)

在pyspark中,我正在努力实现以下逻辑。
假设我有这样一个表(df):

type count
    A    5000
    B    5000
    C    200
    D    123
    ...  ...
    ...  ...
    Z    453

我怎样才能把这一栏加起来 count 按类型 A , B 所有其他类型都属于 Others 类别?
我现在有:

df = df.withColumn('type', when(col("type").isnot("A", "B"))

我的预期结果如下:

type  count
A     5000
B     5000
Other 3043
huus2vyu

huus2vyu1#

要按when表达式分组并求和计数:

from pyspark.sql import functions as F

df1 = df.groupBy(
    when(
        F.col("type").isin("A", "B"), F.col("type")
    ).otherwise("Others").alias("type")
).agg(
    F.sum("count").alias("count")
)

df1.show()

# +------+-----+

# |  type|count|

# +------+-----+

# |     B| 5000|

# |     A| 5000|

# |Others|  776|

# +------+-----+
mjqavswn

mjqavswn2#

您可以根据类型将Dataframe分为两部分,为第二部分聚合一个和,然后执行 unionAll 把它们结合起来。

import pyspark.sql.functions as F

result = df.filter("type in ('A', 'B')").unionAll(
    df.filter("type not in ('A', 'B')")
      .select(F.lit('Other'), F.sum('count'))
)

result.show()
+-----+-----+
| type|count|
+-----+-----+
|    A| 5000|
|    B| 5000|
|Other|  776|
+-----+-----+

相关问题