gpt4 book ai didi

scala - 用于合并的 Spark 结构类型

转载 作者:行者123 更新时间:2023-12-01 13:34:44 25 4
gpt4 key购买 nike

我使用 Spark 2.0.1 Scala 2.11

如何使用 coalesceStructType 的列提供默认值?

说...

val ss = new StructType().add("x", IntegerType).add("y", IntegerType)

val s = new StructType()
.add("a", IntegerType)
.add("b", ss)

val d = Seq( Row(1, Row(1,2)), Row(2, Row(2,3)), Row(2, null) )

val rd = sc.parallelize(d)
val df = spark.createDataFrame(rd, s)

现在,df.select($"b").show 结果

+-----+
| b |
+-----+
|[1,2]|
|[2,3]|
| null|
+-----+

我的问题是如何使用 coalesce 提供默认值(比如 [0,0])?

最佳答案

您可以使用 struct 函数,传递两个 lit(0) 值以匹配您已有的结构的名称:

df.select(coalesce($"b", struct(lit(0).as("x"), lit(0).as("y"))))
.show()

// +---------------------------------------+
// |coalesce(b, struct(0 AS `x`, 0 AS `y`))|
// +---------------------------------------+
// | [1,2]|
// | [2,3]|
// | [0,0]|
// +---------------------------------------+

关于scala - 用于合并的 Spark 结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44377095/

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