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

问题描述 投票:1回答:2

给出一个带有数组列表的数据框

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.;;
apache-spark pyspark apache-spark-sql pyspark-sql
2个回答
2
投票

您可以结合使用transformarray_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返回的所有项目,并以逗号分隔。


-1
投票

在此处爆炸可能有用

import org.apache.spark.sql.functions._
df.select(explode("items")).select("col.*")
© www.soinside.com 2019 - 2024. All rights reserved.