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

Databricks执行Spark代码报错:NameError: name 'expr' is not defined求助

解决Databricks中Spark代码NameError: name 'expr' is not defined报错

报错原因

expr是PySpark提供的函数,用于将SQL表达式转换为Spark的Column对象,但使用前必须先从pyspark.sql.functions模块中导入,否则Python解释器无法识别该名称。

解决方案

方案1:导入expr函数

在代码开头添加导入语句,保留原有SQL表达式逻辑:

%python
from pyspark.sql.functions import expr
df = sql("select * from xxxxxxx.xxxxxxx")
transfromWithCol = df.withColumn("MyTestName", expr("case when first_name = 'Peter' then 1 else 0 end"))

方案2:使用PySpark原生API替代SQL表达式

如果更习惯PySpark的函数式写法,可直接用when和col函数实现相同逻辑,无需依赖expr:

%python
from pyspark.sql.functions import when, col
df = sql("select * from xxxxxxx.xxxxxxx")
transfromWithCol = df.withColumn("MyTestName", when(col("first_name") == "Peter", 1).otherwise(0))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:34:57