【问题标题】:Spark Scala Aggregate Function to Find number of occurrence of a column value in a groupSpark Scala聚合函数查找组中列值的出现次数
【发布时间】:2019-02-22 20:44:50
【问题描述】:

我有以下数据:

group_id    id  name
----        --  ----
G1          1   apple
G1          2   orange
G1          3   apple
G1          4   banana
G1          5   apple
G2          6   orange
G2          7   apple
G2          8   apple

我想在每个组中找到唯一的出现次数。到目前为止,我已经这样做了

val group = Window.partitionBy("group_id")
newdf.withColumn("name_appeared_count", approx_count_distinct($"name").over(group))

我想要这样的结果:

group_id    id  name   name_appeared_count
----        --  ----   -------------------
G1          1   apple       3
G1          2   orange      1
G1          3   apple       3
G1          4   banana      1
G1          5   apple       3
G2          6   orange      1
G2          7   apple       2
G2          8   apple       2

提前致谢!

【问题讨论】:

  • 您的方法遇到了什么问题?
  • 它让我完全独一无二。例如对于 G1,我将为所有 5 条记录获得 3 条记录,因为有 3 个不同的项目,根据文档,这是正确的。但无法弄清楚我如何才能得到我想要的
  • 看来你需要groupby,partitionby by multiple cols。

标签: scala apache-spark window partition


【解决方案1】:

方法 approx_count_distinct($"name").over(group) 每组计数不同的 name,因此根据您的预期输出,这不是您想要的。在partition("group_id", "name") 上使用count("name") 将产生所需的计数:

import org.apache.spark.sql.functions._
import org.apache.spark.sql.expressions.Window

val df = Seq(
  ("G1", 1, "apple"),
  ("G1", 2, "orange"),
  ("G1", 3, "apple"),
  ("G1", 4, "banana"),
  ("G1", 5, "apple"),
  ("G2", 6, "orange"),
  ("G2", 7, "apple"),
  ("G2", 8, "apple")
).toDF("group_id", "id", "name")

val group = Window.partitionBy("group_id", "name")

df.
  withColumn("name_appeared_count", count("name").over(group)).
  orderBy("id").
  show
// +--------+---+------+-------------------+
// |group_id| id|  name|name_appeared_count|
// +--------+---+------+-------------------+
// |      G1|  1| apple|                  3|
// |      G1|  2|orange|                  1|
// |      G1|  3| apple|                  3|
// |      G1|  4|banana|                  1|
// |      G1|  5| apple|                  3|
// |      G2|  6|orange|                  1|
// |      G2|  7| apple|                  2|
// |      G2|  8| apple|                  2|
// +--------+---+------+-------------------+

【讨论】:

  • 完美!这么简单的事!非常感谢 Leo C
猜你喜欢
  • 2021-04-07
  • 2021-11-28
  • 2011-12-03
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多