【问题标题】:Problem with UDF in Spark - TypeError: 'Column' object is not callableSpark 中的 UDF 问题 - TypeError: 'Column' object is not callable
【发布时间】:2021-09-26 00:03:49
【问题描述】:

大家好!
我有一个包含 2510765 行 的数据框,其中包含具有相对分数的应用程序评论并具有以下结构:

root
 |-- content: string (nullable = true)
 |-- score: string (nullable = true)

我写了这两个函数,从文本中删除标点符号和表情符号:

import string

def remove_punct(text):
    return text.translate(str.maketrans('', '', string.punctuation))

import re

def removeEmoji(text):
    regrex_pattern = re.compile(pattern = "["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           "]+", flags = re.UNICODE)
    return regrex_pattern.sub(r'',text)

我使用 udf 函数从我为删除标点符号和表情符号定义的函数开始创建一个 spark 函数:

from pyspark.sql.functions import udf

punct_remove = udf(lambda s: remove_punct(s))

removeEmoji = udf(lambda s: removeEmoji(s))

但我收到以下错误:

TypeError                                 Traceback (most recent call last)

<ipython-input-29-e5d42d609b59> in <module>()
----> 1 new_df = new_df.withColumn("content", remove_punct(df_merge["content"]))
      2 new_df.show(5)

<ipython-input-21-dee888ef5b90> in remove_punct(text)
      2 
      3 def remove_punct(text):
----> 4     return text.translate(str.maketrans('', '', string.punctuation))
      5 
      6 

TypeError: 'Column' object is not callable

如何解决?是否有另一种方法可以使用户编写的函数在数据帧上运行?
谢谢 ;)

【问题讨论】:

    标签: python python-3.x dataframe apache-spark pyspark


    【解决方案1】:

    堆栈跟踪表明您是直接调用 python 方法,而不是 udf。

    remove_punct 是一个普通的 Python 函数,而 punct_remove 是一个 udf,可用作 withColumn 调用的第二个参数。

    解决问题的一种方法是在withColumn 调用中使用punct_remove 而不是remove_punct

    另一种减少将 Python 函数与 udf 混淆的机会的方法是使用 @udf 注释:

    from pyspark.sql import functions as F
    from pyspark.sql import types as T
    
    @F.udf(returnType=T.StringType())
    def remove_punct(text):
        return text.translate(str.maketrans('', '', string.punctuation))
    
    df.withColumn("content", remove_punct(F.col("content"))).show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2019-03-13
      • 2021-06-02
      • 2018-03-31
      • 2021-10-22
      • 1970-01-01
      • 2018-08-21
      相关资源
      最近更新 更多