如何从Spark DataFrame的StructType提取首字段构建字典?
从Spark DataFrame的StructType Schema生成指定字典
可以通过遍历StructType中的字段,筛选出类型为嵌套StructType的字段,再提取其第一个子字段名称来构建目标字典,代码实现如下:
from pyspark.sql.types import StructType, StructField def extract_nested_first_field(schema: StructType) -> dict: result = {} for field in schema.fields: # 判断当前字段是否为嵌套StructType类型 if isinstance(field.dataType, StructType): # 取第一个子StructField的name作为值 if field.dataType.fields: result[field.name] = field.dataType.fields[0].name return result
代码说明
- 遍历传入的
StructType的所有StructField元素 - 对每个字段,检查其
dataType是否为StructType(即嵌套结构) - 若为嵌套结构且存在子字段,就以父字段的
name为键,第一个子字段的name为值存入结果字典
示例验证
针对你提供的示例Schema:
root |-- field_1: int |-- field_2: int |-- field_3: struct | |-- date: date | |-- timestamp: timestamp |-- field_4: int
调用上述函数后,返回结果为:
{"field_3": "date"}
内容的提问来源于stack exchange,提问作者marcin2x4
相关产品推荐
相关产品推荐

