【发布时间】:2021-11-23 17:55:18
【问题描述】:
我在 Databricks 中有一个表,其中有一列作为字符串字典,如下所示 -
+---+--------------------------------------------------------------------------------------------------------------+
|id |stringDictionary |
+---+--------------------------------------------------------------------------------------------------------------+
|abc|{"col1": "someValue", "col2" : "someValue", "col3" : "someValue"} |
|def|{"col1" : "someValue", "col3": "someValue"} |
|mnp|{"col1" : "someValue", "col2" : "someValue", "col3" : "someValue", "col4" : "someValue", "col5" : "someValue"}|
|abc|{"col4" : "someValue", "col5" : "someValue", "col6" : "someValue"} |
+---+--------------------------------------------------------------------------------------------------------------+
现在每个 id 都可以有多个结构,如图所示。
我尝试为其中几个定义 Struct 架构,如下所示 -
from pyspark.sql.types import StructType,StructField, StringType
from pyspark.sql.functions import col,from_json
schema = StructType([
StructField("col1",StringType(),True),
StructField("col2",StringType(),True),
StructField("col3",StringType(),True),
StructField("col4", StringType(), True)
])
dfJSON = sparkDF.withColumn("jsonData",from_json(col("stringDictionary"),schema)) \
.select("stringDictionary","jsonData.*","*")#.drop("stringDictionary")
display(dfJSON)
但这不是一个好方法,因为每次添加新元素时都不够用,必须手动更改架构。
有没有办法处理所有此类情况或在读取此表或数据帧时猜测结构架构并将其对应的stringDictionary 展平为自己的单独列?
请帮忙。
【问题讨论】:
标签: python arrays python-3.x apache-spark pyspark