【问题标题】:Apache Spark UDF - Why User Defined Function returning wrong valueApache Spark UDF - 为什么用户定义的函数返回错误的值
【发布时间】:2022-08-03 13:45:58
【问题描述】:

问题:当我调用User Defined Function (UDF) 时,似乎我在以下代码中没有做正确的事情。为什么输出不是“这是一个测试”?

评论:我正在使用python notebook in Azure Databricks`。

笔记本单元格1:

def TestFunction(myVal):
  return \"this is a \" + myVal

笔记本单元格2:

from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType,DateType,StringType

new_name = F.udf(TestFunction, StringType())

s = new_name(\"test\")

print(s)

输出:

Column<\'TestFunction(test)\'>

期望的输出:

This is a test
  • 在select() 或withColumn() 中使用new_test() 作为pyspark 函数。它返回具有所需值的列
  • 您需要将列名传递到此 udf。然后列的值将在 udf 中使用。结果将是一列。

标签: python python-3.x apache-spark pyspark azure-databricks


【解决方案1】:

抱歉,Scala 中的示例

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.{col, udf}
import spark.implicits._
val new_name = udf((myVal: String) => { "this is a " + myVal })

val df = Seq(
  (1, "test1"),
  (2, "test2"),
  (3, "test3"),
  (4, "test4"),
  (5, "test5")
).toDF("id", "name")

val res = df.withColumn("new_name", new_name(col("name")))

res.show(false)
//    +---+-----+---------------+
//    |id |name |new_name       |
//    +---+-----+---------------+
//    |1  |test1|this is a test1|
//    |2  |test2|this is a test2|
//    |3  |test3|this is a test3|
//    |4  |test4|this is a test4|
//    |5  |test5|this is a test5|
//    +---+-----+---------------+

【讨论】:

  • 我不知道斯卡拉。但我对您的 Scala 示例表示赞成 (+1)。
猜你喜欢
  • 2022-11-29
  • 2021-10-28
  • 2017-11-01
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
相关资源
最近更新 更多