PySpark when链式条件按书写顺序执行失效问题咨询
PySpark链式when执行异常原因解析
问题复现代码
Df1 = df.withColumn( "sales", when(col("sales").isNull(), 10) .when(col("sales") == 0, 7) .when(col("sales") > 5, 3) .when((col("sales") < 5) & (col("sales") != 0), 5) .when(col("ISM").isNull(), 50) .when((col("ISM").isNotNull()) & (col("ECR") != "MO"), 50) .when( (col("ISM").isNull()) & (col("ECR") == "MO") & (col("SER") > 0) & (col("SER") <= 1), 5, ) .otherwise(col("sales")), )
核心原因
PySpark的when链式调用遵循短路匹配规则:只要按书写顺序匹配到第一个判定为真的条件,就会直接返回该条件对应的取值,后续所有when的条件都会被直接跳过,不会执行。
你当前代码的条件书写顺序有问题:所有判断sales字段的条件都放在了判断ISM、ECR字段的条件之前。当sales值处于0到5之间时,已经命中了第4个when的条件(col("sales") < 5) & (col("sales") != 0),直接返回值5,后面针对ISM为空的赋值逻辑完全不会触发,自然不会出现你预期的覆盖效果。
修复方案
如果需要ISM、ECR相关的规则优先级更高,能够覆盖sales字段的基础赋值结果,有两种实现方式:
- 调整条件顺序:把优先级更高的规则(也就是需要覆盖的规则)放到链式
when的前面书写 - 拆分计算步骤:分两次调用
withColumn,第一次先计算sales的基础值,第二次用高优先级的规则覆盖更新sales取值,示例如下:
# 第一步:计算sales基础值 df_step1 = df.withColumn( "sales", when(col("sales").isNull(), 10) .when(col("sales") == 0, 7) .when(col("sales") > 5, 3) .when((col("sales") < 5) & (col("sales") != 0), 5) .otherwise(col("sales")) ) # 第二步:用ISM、ECR等高优先级规则覆盖更新sales Df1 = df_step1.withColumn( "sales", when(col("ISM").isNull(), 50) .when((col("ISM").isNotNull()) & (col("ECR") != "MO"), 50) .when( (col("ISM").isNull()) & (col("ECR") == "MO") & (col("SER") > 0) & (col("SER") <= 1), 5, ) .otherwise(col("sales")) )
内容的提问来源于stack exchange,提问作者Amy Jack
相关产品推荐
相关产品推荐

