【问题标题】:pyspark dataframe array of struct to columns结构到列的pyspark数据帧数组
【发布时间】:2022-08-10 22:55:19
【问题描述】:

我有一个数据框:

\"abc\": array [
    \"def\": struct {
        \"id\": string,
        \"value\": string
    }
]

id 可以是 \"PHONE\"、\"FAX\" 和 \"MAIL\" 所以,这是一个示例:

technical_id column_to_explode
1 [[\"PHONE\", \"083665xxxx\"], [\"FAX\", \"0325xxxxxx\"]]
2 [[\"MAIL\", \"abc@xxx.com\"]]
3 null

是否可以转换为:

technical_id column_to_explode PHONE FAX MAIL
1 [[\"PHONE\", \"083665xxxx\"], [\"FAX\", \"0325xxxxxx\"]] 083665xxxx 0325xxxxxx null
2 [[\"MAIL\", \"abc@xxx.com\"]] null null abc@xxx.com
3 null null null null

我正在尝试爆炸,但它重复行,我宁愿避免这种情况。

谢谢。

  • 那么,结构的第一个元素是预期的列名,第二个元素是它的值?
  • 是的,将第一个元素转换为列标题,将第二个元素转换为值
  • 你试过explode然后pivot吗?喜欢this

标签: pyspark aws-glue


【解决方案1】:

您可以在 explode 之后执行 pivot 以确保唯一的 ID 列。这是一个例子。

spark.sparkContext.parallelize([([('phone', 'abc'), ('email', 'xyz')], 1), ([('fax', 'klm')], 2)]). \
    toDF(['arr_of_structs', 'id']). \
    selectExpr('*', 'inline(arr_of_structs)'). \
    groupBy('id'). \
    pivot('_1'). \
    agg(func.first('_2')). \
    show(truncate=False)

# +---+-----+----+-----+
# |id |email|fax |phone|
# +---+-----+----+-----+
# |1  |xyz  |null|abc  |
# |2  |null |klm |null |
# +---+-----+----+-----+

输入数据框如下所示

spark.sparkContext.parallelize([([('phone', 'abc'), ('email', 'xyz')], 1), ([('fax', 'klm')], 2)]). \
    toDF(['arr_of_structs', 'id']). \
    show(truncate=False)

# +----------------------------+---+
# |arr_of_structs              |id |
# +----------------------------+---+
# |[{phone, abc}, {email, xyz}]|1  |
# |[{fax, klm}]                |2  |
# +----------------------------+---+

# root
#  |-- arr_of_structs: array (nullable = true)
#  |    |-- element: struct (containsNull = true)
#  |    |    |-- _1: string (nullable = true)
#  |    |    |-- _2: string (nullable = true)
#  |-- id: long (nullable = true)

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2021-07-08
    • 2020-06-10
    • 2018-03-21
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多