繁体   English   中英

Spark:如何将列的 ArrayType 中的单列收集到不同的数组?

[英]Spark: How to collect a single column from an ArrayType of columns to a different array?

我有一个名为requests的列,它是 ArrayType 和其中的一些字段,例如codevalue

StructField(requests,ArrayType(StructType(StructField(code,IntegerType,true), StructField(value,DoubleType,true) .....)

所以像[[1, 5.0....], [2, 0, ....]]等。

如何只收集数组中的code字段,以便只得到[1,2....] 我对requests中的其他字段不感兴趣。

我尝试使用array_zip但这没有帮助:

val result = df.withColumn("new_col", arrays_zip(col("requests.code")))

我必须使用explode吗? 或者这可能使用高阶函数吗? 提前致谢!

您可以对 Spark >= 2.4 使用更高阶的 function transform

val result = df.withColumn("new_col", expr("transform(requests, x -> x.code)"))

如果您的 Spark >= 3.0,您还可以使用 Scala dataframe API transform

val result = df.withColumn("new_col", transform(col("requests"), x => x("code")))

// or more simply
val result = df.withColumn("new_col", transform(col("requests"), _("code")))

您可以通过访问requests数组中的字段直接获取code值数组:

val result = df.withColumn("new_col", col("requests")("code"))

或者通过使用列方法getItemgetField

val result = df.withColumn("new_col", col("requests").getField("code"))

例子:

result.show(false)
//+----------------------------------------+------------+
//|requests                                |new_col     |
//+----------------------------------------+------------+
//|[[1, 1.5], [2, 2.5], [3, 3.5], [4, 4.5]]|[1, 2, 3, 4]|
//+----------------------------------------+------------+

暂无
暂无

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

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