Pyspark 将数组列表转换为字符串列表

Pyspark transfrom list of array to list of strings

给定一个包含数组列表的数据框

Schema 
|-- items: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- quantity: string (nullable = true)

+-------------------------------+
|items                          |
+-------------------------------+
|[[A, 1], [B, 1], [C, 2]]       |
---------------------------------

如何获取字符串:

+-------------------------------+
|items                          |
+-------------------------------+
|A, 1, B, 1, C, 2               |
---------------------------------

尝试过:

df.withColumn('item_str', concat_ws(" ", col("items"))).select("item_str").show(truncate = False)

错误:

: org.apache.spark.sql.AnalysisException: cannot resolve 'concat_ws(' ', `items`)' due to data type mismatch: argument 2 requires (array<string> or string) type, however, '`items`' is of array<struct<name:string,quantity:string>> type.;;

Explode 在这里可能会有用

import org.apache.spark.sql.functions._
df.select(explode("items")).select("col.*")

您可以使用 transform and array_join 内置函数的组合来实现:

from pyspark.sql.functions import expr

df.withColumn("items", expr("array_join(transform(items, \
                                i -> concat_ws(',', i.name, i.quantity)), ',')"))

我们使用 transform 在项目之间进行迭代,并将每个项目转换为 name,quantity 的字符串。然后我们使用 array_join 连接所有的项目,由 transform 返回,用逗号分隔。