Introduction to PySpark
Benjamin Schmidt
Data Engineer
UDF (User-Defined Function): custom function to work with data using PySpark dataframes
Advantages of UDFs:
All PySpark UDFs need to be registered via the udf()
function.
# Define the function def to_uppercase(s): return s.upper() if s else None
# Register the function to_uppercase_udf = udf(to_uppercase, StringType())
# Apply the UDF to the DataFrame df = df.withColumn("name_upper", to_uppercase_udf(df["name"]))
# See the results df.show()
Remember: UDFs allow you to apply custom Python logic on PySpark DataFrames
from pyspark.sql.functions import pandas_udf
@pandas_udf("float")
def fahrenheit_to_celsius_pandas(temp_f):
return (temp_f - 32) * 5.0/9.0
udf()
Introduction to PySpark