Sub topic 18
When to use a UDF, and when not to
This chapter assumes you can read a DataFrame, add columns with withColumn, and use functions from pyspark.sql.functions. It covers two escape hatches from Spark's built-in engine: user-defined functions (UDFs) and conversion to pandas. Both work, and both cost something.
When to use a UDF, and when not to
A UDF is a Python function that Spark calls on each row. Spark cannot look inside it. The optimizer cannot push filters through it or rewrite it. A regular Python UDF also moves every row between the JVM (the Java runtime Spark runs on) and a Python worker process, which is slow.
Start with the built-in functions. They run inside the engine and the optimizer understands them.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[(1, "alice", 120.0), (2, "bob", 75.5), (3, "carol", None)],
"order_id INT, customer STRING, amount DOUBLE",
)
# Built-in: fast and optimizable
with_tier = orders.withColumn(
"tier",
F.when(F.col("amount") >= 100, "high")
.when(F.col("amount") >= 50, "medium")
.otherwise("low"),
)
display(with_tier)Reach for a UDF only when no combination of built-ins expresses the logic, for example when you must call a Python library on a value. If you need one, prefer a pandas UDF. It receives a whole batch of values as a pandas Series, so the per-row overhead mostly disappears.
import pandas as pd
from pyspark.sql.functions import pandas_udf, udf
@udf("string")
def shout(name):
return None if name is None else name.upper() + "!"
@pandas_udf("string")
def shout_batch(names: pd.Series) -> pd.Series:
return names.str.upper() + "!"
display(orders.select("customer", shout("customer").alias("row_udf"), shout_batch("customer").alias("batch_udf")))Both give the same result here, and F.upper plus F.concat would be faster than either.
Moving data to pandas safely
toPandas() is an action. It collects the whole DataFrame onto the driver, the single machine running your notebook. If the data is larger than the driver's memory, the cell fails with an out-of-memory error.
Reduce the data first, then convert.
summary = (
orders
.groupBy("customer")
.agg(F.sum("amount").alias("total_amount"))
)
pdf = summary.toPandas() # small, aggregated result: safe
sample = orders.limit(1000).toPandas() # bounded size: safe
print(pdf.head())Safe habits:
- Filter, aggregate or
limitbefore callingtoPandas(). - Check
df.count()first if you are unsure of the size. - Keep the heavy work in Spark and use pandas only for the final small step, such as plotting.
Exercise
A teammate writes a plain Python UDF that lowercases a string column, then calls toPandas() on a 500 million row DataFrame to look at the result. What two changes would you suggest?
Show answer
Replace the UDF with the built-in F.lower, which the optimizer can handle and which avoids moving rows to Python. Then reduce the data before converting, for example with limit(1000) or an aggregation, so the driver does not run out of memory.