Rod*_*ney 6 python user-defined-functions apache-spark pyspark azure-databricks
我将 Spark 与 Databricks 一起使用,并具有以下代码:
def replaceBlanksWithNulls(column):
return when(col(column) != "", col(column)).otherwise(None)
Run Code Online (Sandbox Code Playgroud)
接下来的两个语句都有效:
x = rawSmallDf.withColumn("z", replaceBlanksWithNulls("z"))
Run Code Online (Sandbox Code Playgroud)
并使用 UDF:
replaceBlanksWithNulls_Udf = udf(replaceBlanksWithNulls)
y = rawSmallDf.withColumn("z", replaceBlanksWithNulls_Udf("z"))
Run Code Online (Sandbox Code Playgroud)
从文档中我不清楚什么时候应该使用一个而不是另一个,为什么?
AnUDF本质上可以是任何类型的函数(当然也有例外) - 没有必要使用 Spark 结构,例如when、col等。通过使用 anUDF函数replaceBlanksWithNulls可以编写为普通的 python 代码:
def replaceBlanksWithNulls(s):
return "" if s != "" else None
Run Code Online (Sandbox Code Playgroud)
注册后可以在数据框列上使用:
replaceBlanksWithNulls_Udf = udf(replaceBlanksWithNulls)
y = rawSmallDf.withColumn("z", replaceBlanksWithNulls_Udf("z"))
Run Code Online (Sandbox Code Playgroud)
注意:an的默认返回类型UDF是字符串。如果需要其他类型,则必须在注册时指定,例如
from pyspark.sql.types import LongType
squared_udf = udf(squared, LongType())
Run Code Online (Sandbox Code Playgroud)
在这种情况下,列操作并不复杂,并且有 Spark 函数可以实现相同的效果(即如replaceBlanksWithNulls问题中所示:
x = rawSmallDf.withColumn("z", when(col("z") != "", col("z")).otherwise(None))
Run Code Online (Sandbox Code Playgroud)
只要有可能,这总是首选,因为它允许 Spark 优化查询,请参阅Spark 函数与 UDF 性能等?
| 归档时间: |
|
| 查看次数: |
2950 次 |
| 最近记录: |