我正在尝试解析JSON并使用Python Spark将列添加到DataFrame:
tableDF = spark.sql("select * from transaction")
stats_df = parseJSONCols(tableDF)
def parseJSONCols(df):
res = df
cols = ['State']
for i in cols:
schema = spark.read
.json(res.rdd.map(lambda x: x[i]))
.schema
res = res.withColumn("selectedState", lit(filterSelectedState(col(i))))
return res
其中State
是具有此结构的JSON字符串:
[
{
isSelected: true,
name: 'x'
},
{
isSelected: false,
name: 'y'
}
]
我想提取isSelected
字段的值,并将其添加到selected
的tableDF
列中。
有人可以帮助我实现这个目标吗?
你可能想要这样的东西:
df = df.withColumn('isSelected', f.col('State').getItem('isSelected'))
但是,看看stats_df.take(2)
的输出会很有用,这样我们就可以看到你正在处理的DF的确切结构。