我正在编写一个udf,它将获取两个dataframe列以及一个额外的参数(一个常量值),并应向dataframe添加一个新列。我的函数看起来像:
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
我想很明显我的问题和这两个问题有什么不同。任何帮助都将不胜感激。
注:
为了便于讨论,我在这里对函数进行了简化,实际函数更复杂。我知道这个手术可以用
when
和
otherwise
声明。