pandas_udf
@pandas_udf takes the Spark return type, and the Python type hints on your function tell Spark which variant you mean. The workhorse takes 1 pd.Series per input column and returns a pd.Series with exactly as many values. Inside, your pandas or numpy code works on the whole Series at once. price * 1.2 multiplies every row of the batch in one vectorized operation, and Spark checks only that the output length matches the input.
The cell below adds a price with 20% VAT to every product that has a price. Run it, then add rating as a second argument and return price * rating: every extra input column arrives as another Series, aligned row for row with the first.
The function sees only its batch
Each call gets 1 batch, so anything that summarizes the Series inside a Series-to-Series UDF summarizes the batch. price - price.mean() subtracts the mean of whichever rows shared the batch, and the answer shifts if the table is repartitioned, the batch cap is raised, or a filter upstream drops rows. Spark raises no error, because the output length still matches. A statistic over a whole column or a whole group belongs in a built-in aggregate joined back to the rows, or in one of the grouped variants below.
This UDF runs over a 3-million-row table stored in 12 partitions, with the default batch cap. What does each output row hold?
@pandas_udf("double")
def centered(price: pd.Series) -> pd.Series:
return price - price.mean()- The row's price minus the mean of its own Arrow batch, which differs from batch to batch
- The row's price minus the mean of all 3 million prices, computed once on the driver
- The row's price minus the mean of its partition, since each task calls the function once
- An error, because a Series-to-Series UDF is not allowed to call an aggregate like mean
The variants and what each costs
| Shape | Each call receives | Called from | Shuffle | Plan node |
|---|---|---|---|---|
| `Series` to `Series` | 1 batch per input column | `select`, `withColumn` | None | `ArrowEvalPython` |
| `Iterator[Series]` to `Iterator[Series]` | Every batch of 1 partition, streamed | `select`, `withColumn` | None | `ArrowEvalPython` |
| `Series` to scalar | Every value of 1 group | `groupBy().agg()`, windows | All rows, no partial aggregation | `AggregateInPandas` |
| `applyInPandas` | 1 whole group as a DataFrame | `groupBy()` | All rows, by key | `FlatMapGroupsInPandas` |
| `mapInPandas` | Every batch of 1 partition as DataFrames | The DataFrame itself | None | `MapInPandas` |
Only rows 3 and 4 add an exchange, because a group has to be complete before Python sees any of it. The remaining rows are narrow and run inside the current stage.
Setup once per partition
from typing import Iterator
import pandas as pd
from pyspark.sql.functions import pandas_udf
@pandas_udf("double")
def risk_score(amounts: Iterator[pd.Series]) -> Iterator[pd.Series]:
weights = load_weights("/models/risk_v3.json")
for amount in amounts:
yield amount * weights["amount"] + weights["bias"]The iterator variant hands your function every batch of 1 partition through a generator, so the line above the for loop runs once per task. The same load inside a Series-to-Series UDF would repeat for every batch: a 400-partition job with 25 batches per partition would read a 200MB model 10,000 times instead of 400. Python workers are reused across tasks by default, so keeping the loaded model in a module-level variable of a module shipped to the executors can cut the loads further, toward 1 per worker.
Groups bring a shuffle and a whole group in memory
A Series-to-scalar UDF in groupBy().agg() and applyInPandas both need every row of a key inside one Python call, so Spark hash-partitions on the grouping key first. Neither combines rows before the exchange: where F.avg sends 1 partial sum and count per key per map task, a pandas aggregate sends every row. On the reducer, the whole group is materialized as one pandas object, so a hot key with 40 million rows becomes a 40-million-row DataFrame in one worker's memory: skew and an OOM risk at the same time.
Below, applyInPandas centers each sensor's readings on that sensor's own mean. Watch where the exchange falls: 2 input tasks hash rows by sensor, and each of the 3 reducer tasks calls center once for every sensor it received.
import pandas as pd
def center(pdf: pd.DataFrame) -> pd.DataFrame:
pdf["centered"] = pdf["value"] - pdf["value"].mean()
return pdf
result = readings.groupBy("sensor").applyInPandas(
center, schema="sensor string, value double, centered double"
)
result.collect()| sensor | value |
|---|---|
| s1 | 20 |
| s2 | 31 |
| s1 | 22 |
| s3 | 15 |
| s2 | 29 |
| s1 | 24 |
| s3 | 17 |
| s2 | 30 |
| s3 | 16 |
The mean is right this time because each group arrives whole: all of sensor s1's readings meet in a single call, so the function finds their mean of 22 and turns 20 into -2 and 24 into 2, with 22 itself landing on 0. The price is the exchange that the plan shows before FlatMapGroupsInPandas, plus enough Python memory to hold the largest group.
About this lesson
This section is part of the UDFs and Serialization: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.