更新结构列 pyspark 中的字段 - withField 不替换

update field in struct column pyspark - withField does not replace

我有一个 table,其中有一列带有日期,我想用它来更新我为新列定义的结构中字段的值。

简单table:

date 
----------
1960-12-01

结构:

value_type = T.StructType(
    [
       T.StructField("extra",T.MapType(T.StringType(), T.StringType(), True), True),
       T.StructField("date", T.StringType(), True),
       T.StructField("from_date", T.StringType(), True),
       T.StructField("to_date", T.StringType(), True),
       T.StructField("value", T.StringType(), True),
    ]
)

我用它来创建一个新的空列,然后我想用这个代码更新它:

dateOfBirth_df = (
  df
 .withColumn("dob_new", (F.lit(None).cast(value_type)))
 .withColumn("dob_new", F.col("dob_new").withField("value", F.lit("date"))))

有效,但 dob_new.date 字段未更新。 有人知道我做错了什么吗?

当你这样做时:

F.lit(None).cast(value_type)

它正在创建一个值为 NULL 的列。所以 withField 对 null 值总是给出 null。

您可以试试这个:

from pyspark.sql import functions as F

dateOfBirth_df = df.withColumn(
    "dob_new",
    F.struct(*[F.lit(None).cast(f.dataType).alias(f.name) for f in value_type.fields])
).withColumn(
    "dob_new",
    F.col("dob_new").withField("value", F.col("date"))
)

dateOfBirth_df.show(truncate=False)
#+----------+------------------------------------+
#|date      |dob_new                             |
#+----------+------------------------------------+
#|1960-12-01|{null, null, null, null, 1960-12-01}|
#+----------+------------------------------------+