【问题标题】:How to use udf and class in pyspark withcolumn如何在pyspark withcolumn中使用udf和class
【发布时间】: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")))

但是, 列

我该怎么做?

【问题讨论】:

    标签: python apache-spark pyspark


    【解决方案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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2022-12-18
      • 1970-01-01
      • 2019-01-25
      • 2021-02-26
      相关资源
      最近更新 更多