给定一个带有数组列表的数据框
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.;;
您可以结合使用transform和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返回的项目,并用逗号分隔。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句