我有下面的数据格式
+----+-------+-----+
|name|subject|score|
+----+-------+-----+
| Tom| math| 90|
| Tom|physics| 70|
| Amy| math| 95|
+----+-------+-----+我使用了collect_list和pyspark.sql.functions中的struct函数
df.groupBy('name').agg(collect_list(struct('subject', 'score')).alias('score_list'))以获得以下数据
+----+--------------------+
|name| score_list|
+----+--------------------+
| Tom|[[math, 90], [phy...|
| Amy| [[math, 95]]|
+----+--------------------+我的问题是如何将最后一列score_list转换为字符串并将其转储到csv文件中,如
Tom (math, 90) | (physics, 70)
Amy (math, 95)非常感谢你的帮助,谢谢。
更新:Here是一个类似的问题,但并不完全相同,因为它直接从string传递到另一个string。在我的例子中,我想首先将collect_list<struct>转换为string,最后将这个collect_list<struct>.压缩
发布于 2019-08-07 16:43:57
根据您的更新和注释,对于Spark 2.4.0+,有一种方法可以使用Spark内置函数来构造一个结构数组:transform和array
>>> df.printSchema()
root
|-- name: string (nullable = true)
|-- score_list: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- subject: string (nullable = true)
| | |-- score: integer (nullable = true)
>>> df.show(2,0)
+----+---------------------------+
|name|score_list |
+----+---------------------------+
|Tom |[[math, 90], [physics, 70]]|
|Amy |[[math, 95]] |
+----+---------------------------+
>>> df1.selectExpr(
"name"
, """
array_join(
transform(score_list, x -> concat('(', x.subject, ', ', x.score, ')'))
, ' | '
) AS score_list
"""
).show(2,0)
+----+--------------------------+
|name|score_list |
+----+--------------------------+
|Tom |(math, 90) | (physics, 70)|
|Amy |(math, 95) |
+----+--------------------------+其中:
x),我们使用concat('(', x.subject, ', ', x.score, ')')将其转换为字符串。|连接起来,这将返回最终的字符串https://stackoverflow.com/questions/57381557
复制相似问题