gpt4 book ai didi

python - Pyspark 将结构数组转换为字符串

转载 作者:行者123 更新时间:2023-12-02 00:53:14 29 4
gpt4 key购买 nike

我在 Pyspark 中有以下数据框

+----+-------+-----+                                                            
|name|subject|score|
+----+-------+-----+
| Tom| math| 90|
| Tom|physics| 70|
| Amy| math| 95|
+----+-------+-----+

我用过collect_liststruct来自 pyspark.sql.functions 的函数

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 。就我而言,我想先转string collect_list<struct> 最后将这个 collect_list<struct> 字符串化

最佳答案

根据您的更新和评论,对于 Spark 2.4.0+,这是使用 Spark SQL 内置函数对结构数组进行字符串化的一种方法:transformarray_join :

>>> 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) |
+----+--------------------------+

地点:

  1. 使用transform()将结构数组转换为字符串数组。对于每个数组元素(结构体x),我们使用concat('(', x.subject, ', ', x.score, ')')来转换将其转换为字符串。
  2. 使用 array_join() 将所有数组元素(StringType)与 | 连接起来,这将返回最终的字符串

关于python - Pyspark 将结构数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381557/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com