gpt4 book ai didi

python - Pyspark:在 UDF 中传递多个列和一个参数

转载 作者:行者123 更新时间:2023-11-28 20:57:33 26 4
gpt4 key购买 nike

我正在编写一个 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())

以上都不适合我。我得到这些想法是基于 thisthis stackoverflow 帖子,我认为很明显我的问题与这两个问题有何不同。任何帮助将不胜感激。

注意:我在这里简化了功能只是为了讨论,实际功能更复杂。我知道可以使用 whenotherwise 语句完成此操作。

最佳答案

您不必使用用户定义的函数。您可以使用函数 when()otherwise() :

from pyspark.sql import functions as f
df = df.withColumn('new_column',
f.when(f.col('col1') == f.col('col2'), f.col('col1'))
.otherwise('other_value'))

另一种方法是生成用户定义的函数。但是,使用 udf 会对性能产生负面影响,因为数据必须在 python 之间进行(反)序列化。要生成用户定义的函数,您需要一个返回(用户定义的)函数的函数。例如:

def generate_udf(constant_var):
def test(col1, col2):
if col1 == col2:
return col1
else:
return constant_var
return f.udf(test, StringType())

df = df.withColumn('new_column',
generate_udf('default_value')(f.col('col1'), f.col('col2')))

关于python - Pyspark:在 UDF 中传递多个列和一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52843485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com