如何在pyspark withcolumn中使用udf和class

Posted

技术标签:

【中文标题】如何在pyspark withcolumn中使用udf和class【英文标题】:How to use udf and class in pyspark withcolumn 【发布时间】:2021-01-26 10:33:42 【问题描述】:

我正在使用 pyspark 但是,我不知道如何使用我的定义类。

class TEST:
    def __init__(self, content):
        self.content

    def my_function(self):
        return self.content + "text"

df.withColumn("test", TEST(content=col("TEST")))

但是,

我该怎么做?

【问题讨论】:

【参考方案1】:

你不能用.withColumn(..)直接调用你的自定义函数,你需要使用UserDefinedFunctions (UDF)

.withColumn 期望第二个参数是列表达式。因此,您可以使用以下方法使用自定义函数,将它们转换为 UDF 并在 .withColumn 内部调用:

from pyspark.sql.functions import udf

udf_func = udf(lambda content : content + "text", StringType())

df_result= df.withColumn("test",udf_func(content))
df_result.show()

或者如果你想上课,你可以做类似的事情:

class TEST:
    def __init__(self, content):
        self.content

    def my_function(self):
        return self.content + "text"

udf_func = udf(lambda content: TEST(content).myfunction(), StringType())
df_result= df.withColumn("test",udf_func(content))

【讨论】:

以上是关于如何在pyspark withcolumn中使用udf和class的主要内容,如果未能解决你的问题,请参考以下文章

为啥'withColumn'在pyspark中需要这么长时间?

在 Pyspark 中的 .withColumn 中编写自定义条件

pyspark Column 不可使用 withColumn 进行迭代

在 Pyspark 中的多个列上使用相同的函数重复调用 withColumn()

如何创建 Pyspark UDF 以向数据框添加新列

PySpark:withColumn() 有两个条件和三个结果