You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:16:00