![](/img/trans.png)
[英]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.