Good for small or simple transforms, but incurs Python↔JVM overhead per row.
python
from pyspark.sql.functions import udf
from pyspark.sql.types import DoubleType, StringType
# 1a. Define your Python function
def f_double(x):
return x * 2 if x is not None else None
# 1b. Wrap it as a Spark UDF
f_double_udf = udf(f_double, DoubleType())
# 1c. Apply to one (or more) columns
df2 = (df
.withColumn("doubled", f_double_udf(df["some_numeric_col"]))
.withColumn("descr", udf(lambda s: s.upper(), StringType())(df["some_str_col"]))
)
df2.display()
Pros: simple Cons: slow per‐row overhead
2) Pandas UDF (vectorized scalar)
Processes batches of rows in one go. Much faster than plain UDFs.
python
import pandas as pd
from pyspark.sql.functions import pandas_udf
from pyspark.sql.types import DoubleType
# 2a. Decorate as Pandas UDF
@pandas_udf(DoubleType())
def f_double_pd(s: pd.Series) -> pd.Series:
# s is a pandas Series of values from one column
return s * 2
# 2b. Apply it exactly like a normal spark func
df3 = df.withColumn("doubled", f_double_pd(df["some_numeric_col"]))
df3.display()
You can also define multi‐argument pandas UDFs:
python
@pandas_udf("double")
def f_weighted(a: pd.Series, b: pd.Series) -> pd.Series:
return a * b
df4 = df.withColumn("weighted", f_weighted(df.a, df.b))
Pros: vectorized speed Cons: slightly more OO magic
3) mapInPandas (batch → batch, full schema)
If your transform needs to see multiple columns and return multiple columns, you can operate on whole pandas DataFrames:
python
from pyspark.sql.types import StructType, StructField, DoubleType, IntegerType
# 3a. Define the output schema
out_schema = StructType([
StructField("id", IntegerType()),
StructField("x", DoubleType()),
StructField("y", DoubleType()),
StructField("sum_xy", DoubleType()),
])
# 3b. The function will receive an iterator of pandas DataFrames
def batch_transform(iterator):
for pdf in iterator:
pdf["sum_xy"] = pdf["x"] + pdf["y"]
yield pdf[["id","x","y","sum_xy"]]
# 3c. Apply
df5 = df.mapInPandas(batch_transform, schema=out_schema)
df5.display()
Pros: full control of multiple cols at once Cons: must manage schema manually
Tips & Best Practices
If you just need one column → use a scalar pandas_udf.
If you’re doing ML‐style feature engineering with many cols → mapInPandas.
Always choose the smallest granularity that meets your needs for best performance.
Benchmark with .timeit() or UI/job details in Databricks.
Pick the approach that best matches your function’s shape and your performance needs! 🚀