UDFs and pandas UDFs
When no built-in function does what you need, you can write your own in Python and use it on a column: a user-defined function, or UDF. This lesson shows how, why plain Python UDFs are slow, how pandas UDFs make them much faster, and how often a built-in can do the job instead.
Step 1 · PySpark functions · Silver · Beyond built-ins, lesson 1 of 2
On this page
Read first: select · Driver, executors and the cluster manager (skip if you know them)
In plain words first
Spark runs on the JVM, Java's engine. A Python UDF is like sending every row by courier to a Python translator in another building, waiting for the answer, and sending it back. Built-in functions are a translator sitting at the same desk.
A pandas UDF sends the rows in big boxes instead of one envelope at a time, which is why it is so much faster.
Writing a UDF
from pyspark.sql.types import StringType @F.udf(returnType=StringType()) def mask_email(email): if email is None: return None user, _, domain = email.partition("@") return user[:1] + "***@" + domain result = users.select("id", mask_email("email").alias("masked")) # Use it from SQL too spark.udf.register("mask_email", mask_email) spark.sql("SELECT id, mask_email(email) AS masked FROM users")
- Declare the return type, and return that type. What happens when the function returns something else depends on the kind of UDF. A classic UDF (rows pickled to Python) silently gives nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →. An Arrow-optimised UDF, the default from Spark 4.2, converts the value where it can (
'5'becomes 5) and raises an error where it cannot. - Handle
Noneyourself: the UDF receives nulls as None. - Spark may call a UDF more or fewer times than you expect (it can be re-run, or evaluated before a filter). Keep it deterministic and free of side effects, or mark it
.asNondeterministic().
Why it is slow
Step 1 · JVM
Step 2 · serialise
Step 3 · Python
Step 4 · back
Step 5 · the cost
pandas UDFs
A pandas UDF (vectorised UDF) receives whole batches as pandas Series, transferred with Apache Arrow, a columnar format both the JVM and Python read without pickling. Your code then uses vectorised pandas or NumPy operations:
import pandas as pd from pyspark.sql.functions import pandas_udf @pandas_udf("double") def with_tax(amount: pd.Series, rate: pd.Series) -> pd.Series: return (amount * (1 + rate)).round(2) result = orders.select("id", with_tax("amount", "tax_rate").alias("gross"))
| Kind | Signature | Use for |
|---|---|---|
| Series to Series | pd.Series → pd.Series | Row-wise maths, string clean-up, model scoring |
| Series to scalar | pd.Series → float | A custom aggregateaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more → in groupBy().agg() |
| applyInPandas | groupBy(...).applyInPandas(fn, schema) | Run a pandas function on each whole group, such as fitting one model per store |
| mapInPandas / mapInArrow | iterator of DataFramesDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more → → iterator | Batch processing with setup cost, such as loading a model once per partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → |
Avoiding UDFs
Before writing a UDF, check the built-ins: the mask above is F.concat(F.substring("email", 1, 1), F.lit("***@"), F.split("email", "@")[1]). Conditions are when, parsing is regexp_extract, element-wise arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more → work is transform, and lookups are joins. Spark 3.5+ also adds Arrow-optimised regular UDFs (useArrow=True), which cut the serialisation cost when a plain UDF is unavoidable.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Clean phone numbers with a pandas UDF, for logic that needs Python, while keeping the work vectorised.
import pandas as pd from pyspark.sql import functions as F @F.pandas_udf("string") def normalise_phone(raw: pd.Series) -> pd.Series: digits = raw.str.replace(r"\D", "", regex=True) # vectorised over a batch return digits.str[-10:].where(digits.str.len() >= 10) contacts = spark.createDataFrame( [(1, "+91 98765-43210"), (2, "(098) 7654 3210"), (3, "12345"), (4, None)], ["id", "phone"]) (contacts.withColumn("phone_10", normalise_phone("phone")) .write.mode("overwrite").parquet("lab/udfs/contacts")) spark.read.parquet("lab/udfs/contacts").orderBy("id").show()
Output from a real run
+---+---------------+----------+ | id| phone| phone_10| +---+---------------+----------+ | 1|+91 98765-43210|9876543210| | 2|(098) 7654 3210|9876543210| | 3| 12345| NULL| | 4| NULL| NULL| +---+---------------+----------+
What to notice:
- Both differently formatted numbers became the same
9876543210: digits only, last 10. 12345is too short, so it becameNULL; a missing phone stayedNULL.- Built-in functions (
regexp_replace,substring) could do this one. Use a pandas UDF when you need a real Python library.
Goal: Time the same calculation as a built-in expression, a Python UDF and a pandas UDF.
import time import pandas as pd from pyspark.sql import functions as F df = spark.range(0, 500_000).withColumn("x", F.col("id") * 1.0) py_udf = F.udf(lambda x: x * 2 + 1, "double") @F.pandas_udf("double") def pandas_double(x: pd.Series) -> pd.Series: return x * 2 + 1 versions = {"built-in": F.col("x") * 2 + 1, "python udf": py_udf("x"), "pandas udf": pandas_double("x")} for name, expr in versions.items(): t = time.time() total = df.select(expr.alias("y")).agg(F.sum("y")).first()[0] print(f"{name}: {time.time() - t:.2f}s, sum={total:.0f}")
Output from a real run
built-in: 0.05s, sum=250000000000 python udf: 0.22s, sum=250000000000 pandas udf: 0.12s, sum=250000000000
What to notice:
- All three give the same sum; only the speed differs.
- The built-in is fastest, the pandas UDF next, the row-by-row Python UDF slowest.
- Run it twice: the first UDF call also pays for starting the Python workers.
Goal: See what happens when a UDF returns a different type from the one it declares.
from pyspark.sql import functions as F # declared int, returns a float pickled = F.udf(lambda x: x * 1.5, "int", useArrow=False) arrow = F.udf(lambda x: x * 1.5, "int", useArrow=True) (spark.range(3) .select("id", pickled("id").alias("pickled_udf"), arrow("id").alias("arrow_udf")) .show())
Output from a real run
+---+-----------+---------+ | id|pickled_udf|arrow_udf| +---+-----------+---------+ | 0| NULL| 0| | 1| NULL| 1| | 2| NULL| 3| +---+-----------+---------+
What to notice:
- Neither UDF raised an error, but both changed the data.
- The classic (pickled) UDF returned
NULLfor every row, even 0.0. - The Arrow UDF (the default from Spark 4.2) turned 1.5 into 1 and 3.0 into 3: silently truncated. Declare return types carefully and test UDFs on a few rows.
Common mistakes
- A UDF for something built in — Upper-casing, regexregular expression: A short pattern that describes what some text looks like, used to find, check or extract parts of strings. Learn more →, date maths and conditions all exist as functions.
- Wrong returnType — Spark returns null instead of raising an error.
- Ignoring None — The function crashes with a Python error on the first null.
- Side effects inside a UDF (API calls, counters) — It may run more than once per row. Use mapInPandas with care, or do it outside Spark.
Key takeaways
- UDFs run Python per row in a separate process.
- Serialisation and the black-box effect make them slow.
- pandas UDFs use Arrow batches and vectorised code.
- Check for a built-in function first.
Interview prep
THE QUESTION
"Why are Python UDFs slow, and what do you do about it?"
Avoid: "Python is slow". Explain serialization between the JVM and Python and that Catalyst cannot optimise inside the function.
Follow-ups · answer out loud, then open
Follow-up"When are pandas UDFs faster than regular Python UDFs?"
Scenario"A UDF parses user agents with a third-party library. It is the slowest stage. Options?"
Trap"A UDF that returns the wrong type raises an error."
int. An Arrow-optimised UDF (the default from Spark 4.2) converts it instead, truncating 1.5 to 1. Either way the data changes without an error, so declare types carefully and test.Check yourself
3 questionsA classic (pickled) UDF declared to return IntegerType returns the Python string "5". What happens?
Show the answer
Spark returns null instead of raising an error. A pickled UDF turns a value of the wrong type into null, silently. (An Arrow-optimised UDF, the default from Spark 4.2, would convert "5" to 5 and fail on "abc".)
What makes pandas UDFs faster than regular UDFs?
Show the answer
Arrow batches and vectorised operations instead of per-row pickling. Data moves in columnar batches and Python works on whole Series.
Why can a filter not be pushed through a UDF?
Show the answer
Catalyst cannot see what the function does. The UDF is a black box to the optimiser.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Beyond built-ins · lesson 2 of 2 · 6 min readTesting PySpark code
Unit test transformations with a local SparkSession and assertDataFrameEqual, and the cases worth covering.
Related lessons
String functionsPySpark functions · 4 min read
Array functionsSpark internals · 6 min read
Python Data Source API
Previous: regexp_extract
Primary sources: functions.udf · pandas UDFs