在这种情况下,struct
是最合适的.请参见下面的示例.
spark.sparkContext.parallelize([('something',), ('foobar',)]).toDF(['a']). \
withColumn('b_c_struct',
func.when(func.col('a') == 'something',
func.struct(func.lit('x').alias('b'), func.lit('y').alias('c'))
)
). \
select('*', 'b_c_struct.*'). \
show()
# +---------+----------+----+----+
# | a|b_c_struct| b| c|
# +---------+----------+----+----+
# |something| {x, y}| x| y|
# | foobar| null|null|null|
# +---------+----------+----+----+
只需在select
后面使用drop('b_c_struct')
即可删除 struct 列并保留各个字段.