PySpark 3.0.0报错NameError: name 'col' is not defined如何解决
报错原因
- PySpark 3.0.0版本中,
pyspark.sql.functions模块的通配符导出规则(即from xxx import *的加载范围)未将col函数纳入导出列表,因此你写的from pyspark.sql.functions import *不会把col加载到当前代码的命名空间中,调用时就会抛出NameError: name 'col' is not defined。 - 从报错只指向
col未定义、没有提示length不存在也能验证:同模块下的length属于通配符导出范围,已经被正常加载,问题仅出在col的导入环节,和业务逻辑、Spark运行环境没有关系。
修复方案
任选以下一种方式修改即可:
- 显式导入
col,替换原有通配符导入为明确导入,避免通配符导入的漏导出问题:
from pyspark.sql.functions import col, length def check_field_length(dataframe: object, name: str, required_length: int): dataframe.where(length(col(name)) >= required_length).show()
- 省略
col包装,直接给length传列名字符串。PySpark内置SQL函数原生支持直接接收列名字符串作为入参,效果和col(name)完全一致:
from pyspark.sql.functions import length def check_field_length(dataframe: object, name: str, required_length: int): dataframe.where(length(name) >= required_length).show()
- 从
pyspark.sql根模块导入col,该路径下的col在所有PySpark 3.x版本中均支持正常导入:
from pyspark.sql import col from pyspark.sql.functions import length def check_field_length(dataframe: object, name: str, required_length: int): dataframe.where(length(col(name)) >= required_length).show()
内容的提问来源于stack exchange,提问作者Volatil3
相关产品推荐
相关产品推荐

