【发布时间】:2018-10-16 20:20:22
【问题描述】:
我正在编写一个 udf,它将采用两个数据框列以及一个额外的参数(一个常量值),并且应该向数据框添加一个新列。我的功能如下:
def udf_test(column1, column2, constant_var):
if column1 == column2:
return column1
else:
return constant_var
另外,我正在执行以下操作以传递多个列:
apply_test = udf(udf_test, StringType())
df = df.withColumn('new_column', apply_test('column1', 'column2'))
除非我删除 constant_var 作为函数的第三个参数,否则这现在不起作用,但我真的需要它。因此,我尝试执行以下操作:
constant_var = 'TEST'
apply_test = udf(lambda x: udf_test(x, constant_var), StringType())
df = df.withColumn('new_column', apply_test(constant_var)(col('column1', 'column2')))
和
apply_test = udf(lambda x,y: udf_test(x, y, constant_var), StringType())
以上都不适合我。我根据this 和this stackoverflow 帖子得到了这些想法,我认为我的问题与两者的不同之处很明显。任何帮助将不胜感激。
注意:我在这里简化了功能只是为了讨论,实际功能更复杂。我知道这个操作可以使用when 和otherwise 语句来完成。
【问题讨论】:
-
你可以使用
.when()和.otherwise(),对吧? -
@Prazy 这个函数实际上更复杂,我把它改成了这个只是为了简化问题。但你是对的,在那种情况下我可以使用 when 和 else
-
什么是 constant_var?
标签: python pyspark user-defined-functions