我正在尝试使用 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

最佳答案

在计算出现次数之前,您需要先对数组进行 explode:查看每个元素的计数:

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

或者只是为了获得不同元素的数量:
val count = dfNew
.withColumn("filtered",explode($"filtered"))
.select($"filtered")
.distinct
.count

关于scala - 如何在 Spark/Scala 中使用 countDistinct?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44886831/

10-12 00:37
查看更多