Why a Python UDF is slow, when a built-in or a pandas UDF is the fix, and how Arrow moves data to pandas.
A Python UDF wraps an ordinary Python function so you can use it as a column expression. Declare the return type — returnType defaults to StringType — as a DataType or a DDL string such as "double".
At run time each executor ships batches of rows to a Python worker, which deserialises them, calls your function once per row and serialises the results back. Inside the function you get plain Python values, with SQL NULL arriving as None. (Since Spark 4.2 the transfer uses Arrow by default instead of pickle, but the function is still called row by row.)
from pyspark.sql import functions as F
from pyspark.sql.types import DoubleType
@F.udf(returnType=DoubleType())
def net_price(price, vat_rate):
if price is None or vat_rate is None:
return None
return round(price / (1 + vat_rate), 2)
sales = sales.withColumn("net", net_price("price", "vat_rate"))Reach the last step for the run summary: the key takeaways from this lesson.