What you will be able to do
- Wrap a Python function with udf or the @udf decorator and apply it to a DataFrame column
- Register a Python function with spark.udf.register so SQL queries can call it by name
- Protect a UDF from null input without relying on predicate evaluation order
- Explain why row-at-a-time Python UDFs are slow and when a pandas UDF is the better choice
Key concept
Row-at-a-time Python UDF — A Python UDF wraps an ordinary Python function so that Spark can apply it to a column. Spark calls the function once for each row, and this per-row call is the reason for both its flexibility and its cost.
1.Creating a Python UDF and calling it from DataFrames and SQL
A Python user-defined function (UDF) lets you apply custom Python logic, such as a normalising rule or a small parser, to a column when no built-in function does the job. A UDF can be called in two ways. The DataFrame API calls a UDF object. SQL calls a registered name. You create each one in a different way, and mixing them up is the most common mistake.
For the DataFrame API, wrap the function with pyspark.sql.functions.udf and pass a return type. Then call the object you get back on a column. If you have a plain normalize_country(code) function, write norm_udf = udf(normalize_country, StringType()) and then df.withColumn("country", norm_udf(df.country)). The @udf decorator does the same wrapping when the function is defined, so the decorated name is already a UDF and you can pass it a column directly.
from pyspark.sql.functions import udf
@udf("long")
def squared_udf(s):
return s * s
df = spark.table("test")
display(df.select("id", squared_udf("id").alias("id_squared")))For SQL, register the function under a name with spark.udf.register(name, function, returnType). SQL text can then call that name. Registering does not change the original Python object. If you call the plain function directly on a column inside withColumn, Spark does not run it once per row: Python runs it once, right away, with a Column object as the argument, so code.strip() fails. A temp view queried through spark.sql can also only use functions that were registered by name. A function that is only defined in the Python session is unknown to SQL.
from pyspark.sql.types import LongType
def squared_typed(s):
return s * s
spark.udf.register("squaredWithPython", squared_typed, LongType())
spark.range(1, 20).createOrReplaceTempView("test")
%sql select id, squaredWithPython(id) as id_squared from testLeaving out the return type does not cause an error. The UDF quietly returns strings. Numeric results then arrive as text, and later arithmetic or comparisons work on strings instead of numbers. You can declare the type as a DataType object such as LongType() or as a DDL string such as "long" or "int". Both forms are accepted by udf, the decorator and spark.udf.register.
Checkpoint 1 of 5· Fill the gap
The function is registered so that the temp view can be queried in SQL. Which name goes in the blank of the SQL query?
from pyspark.sql.types import LongType
def squared_typed(s):
return s * s
spark.udf.register("squaredWithPython", squared_typed, LongType())
spark.range(1, 20).createOrReplaceTempView("test")
%sql select id, ? (id) as id_squared from testSQL can only call a function by the name it was registered under with spark.udf.register, which here is "squaredWithPython". SQL does not know the Python name squared_typed, because that function is only defined in the Python session.
Source: docs.databricks.comCheckpoint 2 of 5· Exam question
A data engineer at a logistics company has a plain Python function:
def normalize_country(code: str) -> str:
return code.strip().upper()
They need to apply it to the country column of a batch DataFrame df using the DataFrame API's .withColumn(). Which code correctly registers and applies the function?
Correct answer: C — norm_udf = udf(normalize_country, StringType())
df = df.withColumn("country", norm_udf(df.country))
- A.
spark.udf.register()only adds the function to the SQL catalog for use insidespark.sql()queries; the raw Python function is still not Column-aware, so calling it directly insidewithColumn()on a Column object fails. - B.
pandas_udfexpects a vectorized function that accepts and returns a pandas Series, butnormalize_countryoperates on a single Python string, so the Arrow-batched Series Spark passes in causes it to fail at execution time. - C. Wrapping the function with
udf()and a return type produces a Column-based function thatwithColumn()can invoke, applying the logic to each row'scountryvalue exactly as intended. - D. The query references
normalize_countryas a SQL function, but the function was never registered withspark.udf.register(), so Spark SQL cannot resolve the name and the query fails to parse.
Sources1
2.Nulls and evaluation order in SQL predicates
A Python UDF receives SQL NULL as Python None. A body such as len(s) or code.strip() then raises an error on the executor, and the task fails. The obvious guard is WHERE s IS NOT NULL AND my_udf(s) > 1, but it is not reliable. Spark SQL does not promise to evaluate the parts of a predicate from left to right, so the UDF can still be called on rows that the null check was supposed to filter out.
Two patterns do hold. The first is to make the UDF null-safe itself, so it returns a sentinel value for None instead of failing. The second is to put the call inside an IF or CASE WHEN branch. Spark evaluates the branch only when its condition is true, so the UDF never sees a null.
spark.udf.register("strlen_nullsafe", lambda s: len(s) if not s is None else -1, "int")
spark.sql("select s from test1 where s is not null and strlen_nullsafe(s) > 1") # ok
spark.sql("select s from test1 where if(s is not null, strlen(s), null) > 1") # okCheckpoint 3 of 5· Check yourself
A nightly SQL job fails with a TypeError from a Python UDF strlen whose body is len(s). The query's filter is WHERE s IS NOT NULL AND strlen(s) > 1. Which change makes the query safe without editing the UDF?
Spark SQL does not promise to evaluate the parts of an AND predicate from left to right, so parentheses or reordering do not stop the UDF from receiving None. When the call sits inside an IF branch, it runs only for rows where the condition is true, so the UDF never sees a null.
“Use IF or CASE WHEN expressions to do the null check and invoke the UDF in a conditional branch”Source: docs.databricks.com
Sources1
3.Why row-at-a-time UDFs are slow, and when a pandas UDF wins
A standard Python UDF is slow because of how often Spark calls it. Spark's engine runs in the JVM, but the function runs in Python. Each row's values go to the Python process, the function is called once for that single value, and the result comes back. On a billion-row DataFrame that means a billion Python calls, each with its own serialization overhead.
A pandas UDF (a function wrapped with pandas_udf that takes and returns pandas Series, covered in Pandas UDFs (pandas_udf)) changes how data travels between the JVM and Python. Spark uses Apache Arrow to send a whole batch of rows in columnar form. The function runs once per batch as a vectorised pandas operation, and Spark joins the batch results back together. Fewer calls and columnar transfer are the whole speed-up. The Python code is not compiled to JVM bytecode or rewritten as a Catalyst expression, and results are not cached across batches.
| Aspect | Python udf | pandas_udf |
|---|---|---|
| Declared with | udf(f, LongType()) or @udf("long") | pandas_udf with Python type hints |
| Function receives | One value per call | A pandas Series per batch |
| Data transfer | Row at a time | Apache Arrow batches |
| Function calls | Once per row | Once per batch, results concatenated |
Choose a pandas UDF when the logic can be written as a whole-column operation, such as a * b or .str.upper() on a Series, and the data is large enough for per-row overhead to dominate. Keep a plain udf when the logic works on one Python value at a time and does not translate to Series operations. A pandas UDF is not a drop-in wrapper either. Passing normalize_country unchanged to pandas_udf breaks, because the function would get a Series, and a Series has no .strip() method.
Checkpoint 4 of 5· Check yourself
A job calls a row-at-a-time Python UDF on a billion-row DataFrame, and a teammate's rewrite with a Series-to-Series pandas_udf runs much faster. What explains the speed-up?
A pandas UDF is faster because Apache Arrow moves data in columnar batches and Spark makes one vectorised call per batch, so there are far fewer Python calls and less per-row serialization. The Python code is not compiled to bytecode or rewritten by Catalyst, and results are not cached across batches.
“is a user-defined function that uses Apache Arrow to transfer data and pandas to work with the data. pandas UDFs allow vectorized operations”Source: docs.databricks.com
Checkpoint 5 of 5· Exam question
What is the primary technical reason a pandas_udf runs faster than an equivalent standard Python udf when processing large DataFrames?
Correct answer: A — It transfers batches between the JVM and Python process using Arrow's columnar format, so the function runs as one vectorized pandas operation instead of many per-row calls.
- A. Arrow-based batching is the actual mechanism: rows are grouped into pandas Series or DataFrames and handed to the function as whole columns, so the function executes once per batch instead of once per row, which is where the speedup comes from.
- B. Vectorized UDFs still run as genuine Python code inside a separate Python process; nothing compiles the function body into JVM bytecode, and the Python interpreter remains fully on the execution path.
- C. There is no built-in output cache for vectorized UDFs; every partition or micro-batch still invokes the function against whatever rows it receives, with no memoization of prior results.
- D. Catalyst can push down certain native SQL functions, but an arbitrary Python function body is never translated into a Catalyst expression, so Python execution remains unavoidable for either kind of UDF.
Sources2
Sources
(2)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/udf/pythonOfficial docs
“Alternatively, you can declare the same UDF using annotation syntax:”
↩︎ Creating a Python UDF and calling it from DataFrames and SQL“You can optionally set the return type of your UDF. The default return type is StringType.”
↩︎ Creating a Python UDF and calling it from DataFrames and SQL“Use IF or CASE WHEN expressions to do the null check and invoke the UDF in a conditional branch”
↩︎ Nulls and evaluation order in SQL predicates“handle subexpression evaluation-order caveats in Spark SQL”
↩︎ Nulls and evaluation order in SQL predicates“You can optionally set the return type of your UDF. The default return type is StringType.”
↩︎ Exam trap 1“Use IF or CASE WHEN expressions to do the null check and invoke the UDF in a conditional branch”
↩︎ Exam trap 2 - 2.https://docs.databricks.com/aws/en/udf/pandasOfficial docs
“uses Apache Arrow to transfer data and pandas to work with the data”
↩︎ Why row-at-a-time UDFs are slow, and when a pandas UDF wins“Spark runs a pandas UDF by splitting the data into batches of rows, calling the function for each batch, and then concatenating the results.”
↩︎ Why row-at-a-time UDFs are slow, and when a pandas UDF wins“pandas UDFs allow vectorized operations that can increase performance up to 100x compared to row-at-a-time Python UDFs.”
↩︎ Key concept“is a user-defined function that uses Apache Arrow to transfer data and pandas to work with the data. pandas UDFs allow vectorized operations”
↩︎ Checkpoint