【问题标题】:Add a column to multilevel nested structure in pyspark在pyspark中向多层嵌套结构添加一列
【发布时间】:2023-01-26 19:45:23
【问题描述】:

我有一个具有以下结构的 pyspark 数据框。

当前架构:

root
 |-- ID
 |-- Information
 |   |-- Name
 |   |-- Age
 |   |-- Gender
 |-- Description

我想将名字和姓氏添加到 Information.Name

有没有办法在 pyspark 中添加新列以便多级结构类型?

预期架构:

root
 |-- ID
 |-- Information
 |   |-- Name
 |   |   |-- firstName
 |   |   |-- lastName
 |   |-- Age
 |   |-- Gender
 |-- Description

【问题讨论】:

    标签: pyspark


    【解决方案1】:

    使用withField,这会起作用:

    df=df.withColumn('Information', F.col('Information').withField('Name', F.struct(*[F.col('Information.Name').alias('FName'), F.lit('').alias('LName')])))
    

    架构之前:

    root
     |-- Id: string (nullable = true)
     |-- Information: struct (nullable = true)
     |    |-- Name: string (nullable = true)
     |    |-- Age: integer (nullable = true)
    

    之后的架构:

    root
     |-- Id: string (nullable = true)
     |-- Information: struct (nullable = true)
     |    |-- Name: struct (nullable = false)
     |    |    |-- FName: string (nullable = true)
     |    |    |-- LName: string (nullable = false)
     |    |-- Age: integer (nullable = true)
    

    我用 Name 的当前值初始化了 Fname 的值,如果需要可以使用 substring。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 2023-03-19
      • 2020-10-04
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多