繁体   English   中英

在 Spark DataFrame 列中获取不同的单词

[英]Get distinct words in a Spark DataFrame column

我有一个这样的df

val df2 = spark.createDataFrame(
  Seq(
    (0, "this is a sentence"),
    (1, "And another sentence")
    )
).toDF("num", "words")

我想在这个专栏中得到不同的词,比如

val vocab = List("this", "is", "a", "sentence", "And", "another")

实现这一目标的 scala/spark-esque 方式是什么?

PS 我知道我可以用 for 循环等来解决这个问题,但我正在努力提高函数式编程,更具体地说是 spark 和 scala。

这是一个非常愚蠢的答案:

import spark.implicits._

df2
  .as[(Int, String)]
  .flatMap { case (_, words) => words.split(' ') }
  .distinct
  .show(false)

我想这就是你想要的?

+--------+
|value   |
+--------+
|sentence|
|this    |
|is      |
|a       |
|And     |
|another |
+--------+

还是您更喜欢包含所有不同单词的单行?

(这也是我第一次堆栈溢出答案,所以请善待<3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM