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

PySpark使用when及otherwise条件语句时出现TypeError等异常如何解决

PySpark when()相关报错排查解决

报错1:TypeError: when() missing 1 required positional argument: 'value'

错误原因

PySpark when() 函数的标准语法为 F.when(判断条件, 条件成立时返回的值),你的代码存在两个语法错误:

  1. 括号位置错误:将本该作为when()第二个入参的窗口计算结果,写到了isin()的入参列表中,导致when()只收到了1个参数,缺少返回值参数。
  2. 表达式结构错误:withColumn()的第二个参数需要是单个完整的Column表达式,你用逗号分隔了两个独立的when()函数,语法不合法。

报错2:java.lang.IllegalArgumentException: otherwise() can only be applied on a Column previously generated by when()

错误原因

括号配对错误:你调整后的代码依然把窗口计算逻辑放在isin()的入参中,且提前闭合了when()函数的括号,导致when()没有收到第二个返回值参数,返回的不是合法的可调用otherwise()的Column对象,调用otherwise()就会触发该错误。


最终修正代码

按照你需要的分支逻辑,正确写法如下:

windowval = (Window.partitionBy('Location').orderBy('month_in_timestamp')
               .rangeBetween(Window.unboundedPreceding, 0))

# 分支1:col1属于data1~data4时返回sum窗口值
# 分支2:col1属于data5~data7时返回avg窗口值
# 其他情况默认返回null,可根据需求修改otherwise的入参
df1 = df.withColumn(
    'NEW_COL',
    F.when(col('col1').isin('data1', 'data2', 'data3', 'data4'), F.sum('col2').over(windowval))
     .when(col('col1').isin('data5', 'data6', 'data7'), F.avg('col2').over(windowval))
     .otherwise(None)
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:39:01