Skip to content
Silver 7 min read · Python 2 practice problems ↓

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

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

PySpark · A Python 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 None yourself: 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

The executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → (a JVM) holds the rows in Spark's internal binary format.

Step 2 · serialise

Rows are converted and pickled, then streamed over a socket to a separate Python worker process.

Step 3 · Python

The Python interpreter calls your function once per row, one value at a time.

Step 4 · back

Results are pickled again and sent back to the JVM, then converted to Spark's format.

Step 5 · the cost

Serialisation both ways plus per-row Python calls typically makes this several times slower than a built-in. And because CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → sees the UDF as a black box, it cannot push filters through it or prune columns it reads.

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:

PySpark · Series to Series
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"))
KindSignatureUse for
Series to Seriespd.Series → pd.SeriesRow-wise maths, string clean-up, model scoring
Series to scalarpd.Series → floatA custom aggregateaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more → in groupBy().agg()
applyInPandasgroupBy(...).applyInPandas(fn, schema)Run a pandas function on each whole group, such as fitting one model per store
mapInPandas / mapInArrowiterator 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 → → iteratorBatch 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.

Note: the in-browser engine does not run UDFs, so these examples are read-only.

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.

Production patternPySpark · When Python is unavoidable: a pandas UDF
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.
  • 12345 is too short, so it became NULL; a missing phone stayed NULL.
  • 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.

ExplorePySpark · Built-in vs Python UDF vs pandas UDF, timed
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.

ExplorePySpark · A UDF that returns the wrong type changes data silently
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 NULL for 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?"

Each row is serialised in the JVM, sent to a Python worker, processed one at a time and sent back, and the optimiser cannot see inside the function. First choice: rewrite with built-in functions (or SQL expressions, transform for arrays). If Python is truly needed, use a pandas UDF so data moves in Arrow batches and the code is vectorised, or mapInPandas to amortise setup like loading a model.

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?"
They receive Arrow batches as pandas Series, so serialization is columnar and your function runs vectorised over thousands of rows at once. Regular UDFs process one row per call (unless Arrow-optimised). The speed-up is largest for numeric work that pandas or NumPy vectorises.
Scenario"A UDF parses user agents with a third-party library. It is the slowest stage. Options?"
Check whether built-ins (regexp_extract) cover the fields you need. If not, use a pandas UDF to amortise overhead, initialise the parser once per worker (module-level or in an iterator UDF), and cache results for repeated user agents, since the number of distinct strings is usually small.
Trap"A UDF that returns the wrong type raises an error."
It does not: a classic (pickled) Python UDF silently returns null when the value does not match the declared type, for example a float from a UDF declared 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 questions

A 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 read
Testing PySpark code
Unit test transformations with a local SparkSession and assertDataFrameEqual, and the cases worth covering.

Related lessons

Previous: regexp_extract

Primary sources: functions.udf · pandas UDFs