Call function on Dataframe's columns has error TypeError: Column is not iterable

Call function on Dataframe's columns has error TypeError: Column is not iterable

我在 Spark 2.4 中使用 Databricks。我正在编码 Python

我创建了这个函数来将 null 转换为空字符串

def xstr(s):
    if s is None:
        return ""
    return str(s)

然后我有下面的代码

from pyspark.sql.functions import *

lv_query = """
  SELECT 
    SK_ID_Site, Designation_Site
  FROM db_xxx.t_xxx 
  ORDER BY SK_ID_Site 
  limit 2"""
lvResult = spark.sql(lv_query)

a = lvResult1.select(map(xstr, col("Designation_Site")))

display(a)

我有这个错误:TypeError: Column is not iterable

我在这里需要做的是为我的 Dataframe 中的每一行调用一个函数。我想将列作为参数传递并得到结果。

Spark 不是这样工作的。您不能将直接 python 代码应用于 spark 数据框内容。 已经有内置函数可以为您完成这项工作。

from pyspark.sql import functions as F

a = lvResult1.select(
    F.when(F.col("Designation_Site").isNull(), "").otherwise(
        F.col("Designation_Site").cast("string")
    )
)

如果你想要一些更复杂的函数,而你不能使用内置函数,你可以使用 UDF,但它可能会影响你的性能(在构建你自己的 UDF 之前最好检查现有的内置函数)。