gpt4 book ai didi

scala - 收集要设置的 Spark 数据帧列值

转载 作者:行者123 更新时间:2023-12-03 08:40:43 25 4
gpt4 key购买 nike

在某些情况下,我需要在 Spark 数据框中将列值收集为 Set(),以查找与其他集合的差异。我有以下 2 个数据框

DF1
+----+---------+----------+----+-----------------+
|Lily|Sunflower|Windflower|Rose|Snapdragon Flower|
+----+---------+----------+----+-----------------+
|1 |2 |3 |4 |5 |
+----+---------+----------+----+-----------------+

DF2
+-----------------+
|Flowers |
+-----------------+
|Rose |
|Lily |
|Tulip |
|Orchid |
|Snapdragon Flower|
+-----------------+

我想找到 DF1 的列名称与 DF2 中 Flower 列的值之间的集合差异。为此,我编写了以下代码,但在它们的设置差异中创建了空值。代码:

import sparkSession.sqlContext.implicits._
val df1 = Seq(("1", "2", "3", "4", "5")).toDF("Lily", "Sunflower", "Windflower", "Rose", "Snapdragon Flower")
val df2 = Seq("Rose", "Lily", "Tulip", "Orchid", "Snapdragon Flower").toDF("Flowers")

val set1 = df1.columns.toSet
println(s"set1 => ${set1}")

val flower_values = df2.select("Flowers").collectAsList()
var set2 = Set("") //introduce empty String Type column
for (i <- 0 until flower_values.size()) {
var col = flower_values.get(i).toString()
set2 += col.substring(1, col.size - 1)
}
println(s"set2 => ${set2}")

val dif_btw_set2_and_set1 = set2.diff(set1)
println(s"dif_btw_set2_and_set1 => ${dif_btw_set2_and_set1}")

输出:

set1 => Set(Sunflower, Rose, Windflower, Snapdragon Flower, Lily)
set2 => Set(, Orchid, Rose, Snapdragon Flower, Tulip, Lily)
dif_btw_set2_and_set1 => Set(, Orchid, Tulip)

这可以在 Scala-Spark 中以更优雅的方式完成吗?

最佳答案

我希望这会有所帮助,它为您提供了 Set 中列的值

val set2 = df2.select("Flowers").as[String].collect().toSet

关于scala - 收集要设置的 Spark 数据帧列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62893981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com