簡體   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