我有一个类似架构的数据框
root
|-- state: struct (nullable = true)
| |-- fld: integer (nullable = true)
我想在
state
中添加列struct,即创建一个具有类似架构的数据框root
|-- state: struct (nullable = true)
| |-- fld: integer (nullable = true)
| |-- a: integer (nullable = true)
但相反,我得到
root
|-- state: struct (nullable = true)
| |-- fld: integer (nullable = true)
|-- state.a: integer (nullable = true)
这是来自尝试
df.withColumn('state.a', val)
最佳答案
这是一种无需使用 udf
即可完成的方法:
# create example dataframe
import pyspark.sql.functions as f
data = [
({'fld': 0},)
]
schema = StructType(
[
StructField('state',
StructType(
[StructField('fld', IntegerType())]
)
)
]
)
df = sqlCtx.createDataFrame(data, schema)
df.printSchema()
#root
# |-- state: struct (nullable = true)
# | |-- fld: integer (nullable = true)
现在使用
withColumn()
并使用 lit()
添加新字段和 alias()
.val = 1
df_new = df.withColumn(
'state',
f.struct(*[f.col('state')['fld'].alias('fld'), f.lit(val).alias('a')])
)
df_new.printSchema()
#root
# |-- state: struct (nullable = false)
# | |-- fld: integer (nullable = true)
# | |-- a: integer (nullable = false)
如果嵌套结构中有很多字段,则可以使用列表推导式,使用
df.schema["state"].dataType.names
获取字段名称。例如:val = 1
s_fields = df.schema["state"].dataType.names # ['fld']
df_new = df.withColumn(
'state',
f.struct(*([f.col('state')[c].alias(c) for c in s_fields] + [f.lit(val).alias('a')]))
)
df_new.printSchema()
#root
# |-- state: struct (nullable = false)
# | |-- fld: integer (nullable = true)
# | |-- a: integer (nullable = false)
引用文献
关于apache-spark - 如何将列添加到 pyspark 数据框中的嵌套结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48777993/