You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Glue作业中将嵌套数组Reasons转为字符串类型?

解决AWS Glue中FilteredOutDecisions.Reasons的类型转换问题

你的Schema中FilteredOutDecisions.Reasons是array<int>类型,由于是嵌套数组结构,无法直接用resolveChoice()处理,需要通过Spark的数组转换函数来实现需求,分两种场景给出方案:

场景1:将Reasons数组中的每个int元素转为string(得到array)

你可以将Glue DynamicFrame转为Spark DataFrame,使用transform()函数遍历数组并转换元素类型,之后再转回DynamicFrame:

from pyspark.sql.functions import transform, col
from awsglue.dynamicframe import DynamicFrame

# 将DynamicFrame转为Spark DataFrame
df = test.toDF()

# 遍历FilteredOutDecisions数组,再遍历内部的Reasons数组转换元素类型
df_updated = df.withColumn(
    "FilteredOutDecisions",
    transform(
        col("FilteredOutDecisions"),
        lambda decision: decision.withField(
            "Reasons",
            transform(decision["Reasons"], lambda reason: reason.cast("string"))
        )
    )
)

# 转回Glue DynamicFrame
test_updated = DynamicFrame.fromDF(df_updated, glueContext, "test_updated")

场景2:将整个Reasons数组拼接为单个字符串(比如用逗号分隔)

如果需要把数组整体转为单个字符串,使用concat_ws()函数拼接数组元素:

from pyspark.sql.functions import transform, col, concat_ws
from awsglue.dynamicframe import DynamicFrame

df = test.toDF()

df_updated = df.withColumn(
    "FilteredOutDecisions",
    transform(
        col("FilteredOutDecisions"),
        lambda decision: decision.withField(
            "Reasons",
            concat_ws(",", decision["Reasons"])
        )
    )
)

test_updated = DynamicFrame.fromDF(df_updated, glueContext, "test_updated")

内容的提问来源于stack exchange,提问作者user12253044

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:16:13