apache-spark - Pyspark 从数组列表转换为字符串列表
问题描述
给定一个带有数组列表的数据框
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 返回,用逗号分隔。
推荐阅读
- c++ - 字符串数组中最长公共子字符串运行时问题
- javascript - 如何将修改后的道具发送到 redux 商店?
- javascript - 在 Body 上反应设置样式
- wordpress - Wordpress 密码保护的上传文件夹
- kubernetes - 部署上的 Kubernetes 流量
- python - 模拟方法 pandas.read_excel 不适用于@patch Python
- r - 从数据框中的列中提取唯一数字
- c++ - 如何限制 Boost.Asio 内存
- php - 我需要使用另一列中的数据更新一列中的数据
- android - 我们应该在 Firebase 中为 ios 和 Android 使用相同的 google-services.json 吗?