首页 > 解决方案 > Spark:如何将列的 ArrayType 中的单列收集到不同的数组?

问题描述

我有一个名为requestsArrayType 的列和其中的一些字段,code例如value

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吗?或者这可能使用高阶函数吗?提前致谢!

标签: scalaapache-sparkpysparkapache-spark-sql

解决方案


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

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]|
//+----------------------------------------+------------+

推荐阅读