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
相关产品推荐
相关产品推荐

