如何将参数传递给用户定义的函数? [英] How to pass the parameter to User-Defined Function?
本文介绍了如何将参数传递给用户定义的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用户定义的功能:
I have a user-defined function:
calc = udf(calculate, FloatType())
param1 = "A"
result = df.withColumn('col1', calc(col('type'), col('pos'))).groupBy('pk').sum('events')
def calculate(type, pos):
if param1=="A":
a, b = [ 0.05, -0.06 ]
else:
a, b = [ 0.15, -0.16 ]
return a * math.pow(type, b) * max(pos, 1)
我需要将参数 param1
传递给此 udf
.我该怎么办?
I need to pass a parameter param1
to this udf
. How can I do it?
推荐答案
您可以将 lit
或 typedLit
用作 udf
的参数像这样:
You can use lit
or typedLit
as a parameter for your udf
like this:
在Python中:
from pyspark.sql.functions import udf, col, lit
mult = udf(lambda value, multiplier: value * multiplier)
df = spark.sparkContext.parallelize([(1,),(2,),(3,)]).toDF()
df.select(mult(col("_1"), lit(3)))
在Scala中:
import org.apache.spark.sql.functions.{udf, col, lit}
val mult = udf((value: Double, multiplier: Double) => value * multiplier)
val df = sparkContext.parallelize((1 to 10)).toDF
df.select(mult(col("value"), lit(3)))
这篇关于如何将参数传递给用户定义的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文