PySpark เบื้องต้น
Benjamin Schmidt
Data Engineer
UDF (User-Defined Function): ฟังก์ชันที่กำหนดเองสำหรับทำงานกับข้อมูลผ่าน PySpark DataFrames
ข้อดีของ 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 ช่วยให้นำ Python logic ที่กำหนดเองไปใช้กับ 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()PySpark เบื้องต้น