
[英]Get the elements from different arraytype columns and build a column with heterogeneous data in Spark
[英]Spark: How to collect a single column from an ArrayType of columns to a different array?
我有一个名为requests
的列,它是 ArrayType 和其中的一些字段,例如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
吗? 或者这可能使用高阶函数吗? 提前致谢!
您可以对 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"))
或者通过使用列方法getItem
, getField
:
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.