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

使用PySpark when-otherwise时遇TypeError:缺少必要位置参数

PySpark when-otherwise 报错解决:TypeError: when() missing 1 required positional argument: 'value'

问题原因

  1. when函数语法错误
    你把when的条件和返回值用额外括号包在了一起,正确的PySpark when语法是when(condition, value),多一层括号会导致参数传递异常,这是触发报错的直接原因。

  2. 列引用错误

  • 无需用DataFrame名称作为列前缀(比如col("new_df0.campaign")),join后的DataFrame直接用列名即可;
  • df1中不存在d1_campaignid列,d1_是new_df0的列别名规则,df1的对应列应该是原始的campaignid;
  • otherwise里的"new_df0.d1_action_curated"是字符串常量,不是列引用,需要用col("d1_action_curated")来指向列。

修正后的代码

df0 = spark.read.option("header", True).csv("dbfs:/FileStore/tables/camp_day0.csv")
df1 = spark.read.option("header", True).csv("dbfs:/FileStore/tables/camp_day1.csv")

def get_aliased_src_columns(day0_df):
    aliased_src_columns = day0_df.select(*(col(column).alias('d1_' + column) for column in day0_df.columns))
    return aliased_src_columns

new_df0 = get_aliased_src_columns(df0)

def join_df1(new_df0, df1):
    join_df1 = new_df0.join(df1,
                            (new_df0.d1_campaign == df1.campaign) & 
                            (new_df0.d1_agencyid == df1.agencyid), 
                            "left") \
                         .select( 
                             col("d1_campaign").alias("campaign").cast("string"), 
                             col("d1_agencyid").alias("agencyid").cast("string"), 
                             when(
                                 col("campaign").isNotNull() & col("campaignid").isNotNull(), 
                                 lit('completed')
                             ).otherwise(col("d1_action_curated")).alias("status")
                         )
    return join_df1

new_df = join_df1(new_df0, df1)

关键修改点

  • 移除when函数中条件和值外层的多余括号,恢复when(condition, value)的正确结构;
  • 修正列引用方式,去掉DataFrame前缀,确保指向正确的列;
  • 将otherwise中的字符串改为列引用,避免返回固定字符串;
  • 补上函数的return join_df1语句,否则调用后会得到None值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:40:20