栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

08-UDFs

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

08-UDFs

User-Defined Functions
  1. Define a function

  2. Create and apply UDF

  3. Register UDF to use in SQL

  4. Use Decorator Syntax (Python Only)

  5. Use Vectorized UDF (Python Only)

Methods
  • UDF Registration (spark.udf): register

  • Built-In Functions : udf

  • Python UDF Decorator : @udf

  • Pandas UDF Decorator : @pandas_udf

Define a function

Define a function in local Python/Scala to get the first letter of a string from the email field.

def firstLetterFunction(email):
  return email[0]

该函数在spark.DataFrame中是无法使用的。

from pyspark.sql.functions import col
display(salesDF.select(firstLetterFunction(col("email"))))

通过udf函数将该函数定义为udf函数后就可以使用了

from pyspark.sql.functions import udf
firstLetterUDF = udf(firstLetterFunction)
display(salesDF.select(firstLetterUDF(col("email"))))

Register UDF to use in SQL

Register UDF using spark.udf.register to create UDF in the SQL namespace.

salesDF.createOrReplaceTempView("sales")

spark.udf.register("sql_udf", firstLetterFunction)
SELECT email,sql_udf(email) AS firstLetter FROM sales

Use Decorator Syntax (Python Only)

Alternatively, define UDF using decorator syntax in Python with the datatype the function returns.

# Our input/output is a string
@udf("string")
def decoratorUDF(email: str) -> str:
  return email[0]
from pyspark.sql.functions import col
salesDF = spark.read.parquet("/mnt/dbswarehouse/raw/sales.parquet")
display(salesDF.select(decoratorUDF(col("email"))))

Use Vectorized UDF (Python Only)
import pandas as pd
from pyspark.sql.functions import pandas_udf

# We have a string input/output
@pandas_udf("string")
def vectorizedUDF(email: pd.Series) -> pd.Series:
  return email.str[0]

# Alternatively
vectorizedUDF = pandas_udf(lambda s: s.str[0], "string")
display(salesDF.select(vectorizedUDF(col("email"))))

We can also register these Vectorized UDFs to the SQL namespace.

spark.udf.register("sql_vectorized_udf", vectorizedUDF)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829231.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号