如何在pyspark数据框中分解字符串类型列并在表中创建单独的列

问题描述 投票:0回答:1

我从 pyspark 中的表加载的数据帧中获取以下值作为字符串。它是嵌套字典列表。我想使用 pyspark 进行爆炸并将它们作为表中的单独列。

dataframe col =  [{ser={cos=hon, mgse=yyyyyyyy, bd=1994-06-11}, ap={}, ep={}}, {ser={cos=null, mgse=null, bd=null}, ap={ncd=035, ccd=A, scd2=C, cos=hon, pgse=nnnnnnn, pcd=06, nar=vvvvvvvv}, ep={eptd=bbbb, ept=bbbb}}]

我想将这些列转换为每次出现的 ser 中的单独列。例如,看看我的预期结果是什么。

enter image description here

我想进一步分解 ap 列和 ep 列,它需要如下所示:

enter image description here

有人可以提供或帮助我如何在来自 redshift 表的字符串格式上实现它。

提前致谢。 巴布

python amazon-web-services apache-spark pyspark aws-glue
1个回答
0
投票

您可以使用 pyspark 中的

from_json
函数来提取内部密钥。您可以参考此link以获取更多示例。

我建议您首先明确定义所需的目标模式,然后尝试使用

from_json
提取信息。特别是因为我可以看到您的列名称中存在潜在的命名冲突,例如,您的
ap
列有一个键
cos
,而存在另一个具有相同名称的单独列。所以你可以尝试以下方法:

from pyspark.sql.functions import from_json, col
from pyspark.sql.types import StructType, StructField, StringType

ap_schema = StructType(
    [
        StructField('ncd', StringType(), True),
        StructField('ccd', StringType(), True),
        StructField('cos', StringType(), True),
        StructField('pgse', StringType(), True)
        # The rest of your desired keys from ap
    ]
)
ep_schema = StructType(
    [
        StructField('eptd', StringType(), True),
        StructField('ept', StringType(), True)
        # The rest of your desired keys from ep
    ]
)

df.withColumn("ap", from_json("ap", ap_schema))\
    .withColumn("ep", from_json("ep", ep_schema))\
    .select(col('id'), col('cos'), col('mgse'), col('bd'), col('ap.*'), col('ep.*'))\
    .show()

根据需要在定义的模式中使用任何类型的 StructFields。

© www.soinside.com 2019 - 2024. All rights reserved.