【发布时间】:2019-03-15 08:35:00
【问题描述】:
这类似于Pyspark: cast array with nested struct to string
但是,接受的答案不适用于我的情况,所以在这里问
|-- Col1: string (nullable = true)
|-- Col2: array (nullable = true)
|-- element: struct (containsNull = true)
|-- Col2Sub: string (nullable = true)
示例 JSON
{"Col1":"abc123","Col2":[{"Col2Sub":"foo"},{"Col2Sub":"bar"}]}
这会在单个列中给出结果
import pyspark.sql.functions as F
df.selectExpr("EXPLODE(Col2) AS structCol").select(F.expr("concat_ws(',', structCol.*)").alias("Col2_concated")).show()
+----------------+
| Col2_concated |
+----------------+
|foo,bar |
+----------------+
但是,如何获得这样的结果或 DataFrame
+-------+---------------+
|Col1 | Col2_concated |
+-------+---------------+
|abc123 |foo,bar |
+-------+---------------+
编辑: 这个解决方案给出了错误的结果
df.selectExpr("Col1","EXPLODE(Col2) AS structCol").select("Col1", F.expr("concat_ws(',', structCol.*)").alias("Col2_concated")).show()
+-------+---------------+
|Col1 | Col2_concated |
+-------+---------------+
|abc123 |foo |
+-------+---------------+
|abc123 |bar |
+-------+---------------+
【问题讨论】:
-
你可以选择"Col1",虽然它不是表达式 df.selectExpr("Col1","EXPLODE(Col2) AS structCol").select("Col1", F.expr("concat_ws (',', structCol.*)").alias("Col2_concated")).show()
-
对不起,这个不行,我在问题里加了原因
标签: pyspark pyspark-sql