pyspark - PySpark 在转换期间创建嵌套结构
问题描述
使用 PySpark,我有一个数据框,其架构类似于以下内容:
root
|-- id: string
|-- v1: string
|-- v2: string
|-- v3: string
我现在想选择数据并将其转换为以下内容:
root
|-- ident: string
|-- custom: struct
| |-- val1: string
| |-- val2: string
| |-- val3: string
我认为这会起作用:
df = (df.withColumn('ident', df['id'])
.withColumn('custom.val1', df['v1'])
.withColumn('custom.val2', df['v2'])
.withColumn('custom.val3', df['v3'])
.select(['ident', 'custom'])
但是,正如您所收集的那样,事实并非如此。任何帮助将不胜感激。
解决方案
您可以使用struct
创建一个结构列:
df.selectExpr('id', 'struct(v1, v2, v3) as custom').printSchema()
root
|-- id: string (nullable = true)
|-- custom: struct (nullable = false)
| |-- v1: string (nullable = true)
| |-- v2: string (nullable = true)
| |-- v3: string (nullable = true)
或使用选择:
import pyspark.sql.functions as f
df.select('id', f.struct(df.v1, df.v2, df.v3).alias('custom')).show()
+---+---------+
| id| custom|
+---+---------+
| a|[b, c, d]|
+---+---------+
数据:
df = spark.createDataFrame([['a', 'b', 'c', 'd']], ['id', 'v1', 'v2', 'v3'])
推荐阅读
- kubernetes - 如何在 nginx 入口中的子路径上公开哨兵?
- php - 如果基本 url 包含端口号,则不会加载资产 - codeigniter 4
- excel - 搜索项目列表的功能
- entity-framework - AddOpenIdConnect 与本地 UserManager
- apache-kafka - Kafka什么时候轮换partition leader?我们有任何财产来控制它吗?
- c - 使用 SVG 在 C 中递归的谢尔宾斯基地毯
- python - python3计数器,它也平均滑动窗口中的索引位置
- python-3.x - 使用用户定义的 python 函数。“ModuleNotFoundError”,Tableau,Tabpy
- django - ImportError:无法导入名称“force_unicode”导致另一个异常
- c# - WPF IsPressed 触发器在鼠标离开按钮时消失