【问题标题】:How do I use countDistinct in Spark/Scala?如何在 Spark/Scala 中使用 countDistinct?
【发布时间】:2017-07-03 13:27:51
【问题描述】:

我正在尝试使用 Scala 在 Spark 数据框中聚合一列,如下所示:

import org.apache.spark.sql._

dfNew.agg(countDistinct("filtered"))

但我得到了错误:

 error: value agg is not a member of Unit

谁能解释一下原因?

编辑:澄清我想要做什么: 我有一列是一个字符串数组,我想计算所有行的不同元素,对任何其他列都不感兴趣。数据:

+------+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
|racist|filtered                                                                                                                                                      |
+------+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
|false |[rt, @dope_promo:, crew, beat, high, scores, fugly, frog, ????????, https://time.com/sxp3onz1w8]                                                                      |
|false |[rt, @axolrose:, yall, call, kermit, frog, lizard?, , https://time.com/wdaeaer1ay]                                                                                |

我想计算过滤,给出:

rt:2, @dope_promo:1, crew:1, ...frog:2 etc

【问题讨论】:

  • 聚合函数需要先申请groupBy。这可以帮助你stackoverflow.com/questions/33500816/…
  • 好的,也许我正在尝试使用错误的功能。我有一列是一个字符串数组,我想计算所有行的不同元素,对任何其他列都不感兴趣。我将编辑我的问题以反映这一点。
  • dfNew.agg(countDistinct("filtered")).show(false) 应该可以解决。
  • 谢谢,但同样的错误。

标签: scala apache-spark dataframe


【解决方案1】:

您需要先explode您的数组才能计算出现次数:查看每个元素的计数:

dfNew
.withColumn("filtered",explode($"filtered"))
.groupBy($"filtered")
.count
.orderBy($"count".desc)
.show

或者只是为了获取不同元素的数量:

val count = dfNew
.withColumn("filtered",explode($"filtered"))
.select($"filtered")
.distinct
.count

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2016-03-27
    • 2019-03-20
    • 2016-12-04
    • 2019-01-25
    • 2019-04-15
    相关资源
    最近更新 更多