What are UDFs in PySpark and how do you define one?
Instruction: Describe User Defined Functions (UDFs) in PySpark and demonstrate how to create one.
Updated
A Python scalar UDF wraps a Python function as a Spark SQL column expression with a declared return type. Define null handling inside the function and return values compatible with that type.
For an existing SparkSession named spark:
from pyspark.sql import functions as F
from pyspark.sql.types import DoubleType
def celsius_to_fahrenheit(value):
return None if value is None else float(value) * 9.0 / 5.0 + 32.0
convert = F.udf(celsius_to_fahrenheit, DoubleType())
temperatures = spark.createDataFrame([(0.0,), (100.0,), (None,)],
"celsius double")
result = temperatures.withColumn("fahrenheit", convert("celsius"))
assert sorted(r.fahrenheit for r in result.filter("celsius IS NOT NULL").collect()) == [32.0, 212.0]
assert result.filter("celsius IS NULL").first().fahrenheit is None
native = temperatures.withColumn("fahrenheit", F.col("celsius") * 9.0 / 5.0 + 32.0)
assert result.exceptAll(native).count() == 0
assert native.exceptAll(result).count() == 0
The built-in arithmetic expression is preferable for this simple conversion because Spark can see its operations and avoid this Python call. The UDF illustrates the API, not a performance recommendation.
Creating F.udf is enough for DataFrame use; registering a SQL function name through spark.udf.register is a separate step when SQL text needs it. Do not rely on a surrounding SQL condition to short-circuit an unsafe UDF. It may be evaluated more or fewer times than expected through optimization or retries; avoid external side effects. Declare true nondeterminism where applicable and test input/return types, nulls and failures. Arrow and pandas UDFs have different execution/type requirements and need their own compatibility checks. Python UDF contract