You need to enable JavaScript to run this app. PySpark调用withColumn新增列传入selectExpr结果报AssertionError如何解决
优惠活动
大模型
产品
解决方案
定价
更多

PySpark调用withColumn新增列传入selectExpr结果报AssertionError如何解决

错误原因

withColumn 方法的第二个入参要求必须是 Column 类型,你传入的 selectExpr 执行后返回的是 DataFrame 对象,类型不匹配因此触发断言报错。

修复方案

方案1(改动最小,兼容原有SQL写法)

使用 expr() 函数将SQL表达式直接转换为Column类型:

from pyspark.sql.functions import expr

orders = ordDtConvDF.withColumn(
    'Status',
    expr('''
        case 
            when order_status in ("CLOSED","COMPLETE") then "completed" 
            when order_status = "PENDING_PAYMENT" then "Pending" 
            else "Processing/canceled" 
        end
    ''')
)

方案2(PySpark原生DSL写法)

使用内置的 when 函数链式判断,不需要写SQL字符串:

from pyspark.sql.functions import when, col

orders = ordDtConvDF.withColumn(
    'Status',
    when(col("order_status").isin("CLOSED","COMPLETE"), "completed")
    .when(col("order_status") == "PENDING_PAYMENT", "Pending")
    .otherwise("Processing/canceled")
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 20:06:03