【发布时间】:2020-11-17 08:39:01
【问题描述】:
我想通过 python3 从 pyspark 数据框中的 json 列中提取数据。
我的数据框:
year month p_name json_col
2010 05 rchsc [{"attri_name": "in_market", "value": "yes"}, {"attri_name": "weight", "value": "12.56"}, {"attri_name" : "color", "value" : "red"} ]
我需要一个像这样的数据框:
year month p_name in_market weight color
2010 05 rchsc yes 12.56 red
我试过了
from pyspark.sql.functions import from_json, col
from pyspark.sql.types import StructType, StructField, StringType
schema = StructType(
[
StructField('attri_name', StringType(), True),
StructField('value', StringType(), True)
]
)
df.withColumn("new_col", from_json("json_col", schema))
但是,不会创建新列。 我不确定如何分解 json 列并将它们转换为新列。
【问题讨论】:
-
我的回答和shu一样,只是在做pivot的时候缩短了一点直接抓取struct的元素。
标签: python json dataframe apache-spark pyspark