PySpark 入門
Benjamin Schmidt
Data Engineer
UDF(User-Defined Function):在 PySpark DataFrame 上處理資料的自訂函式
UDF 優點:
所有 PySpark UDF 都需要透過 udf() 註冊。
# 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()
記住:UDF 可在 PySpark DataFrame 上套用自訂的 Python 邏輯
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() 向 Spark Session 註冊PySpark 入門