繁体   English   中英

Spark 中的 UDF 问题 - TypeError: 'Column' 对象不可调用

[英]Problem with UDF in Spark - TypeError: 'Column' object is not callable

大家好!
我有一个包含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 方法,而不是 udf。

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

解决这个问题的方法之一是使用punct_remove代替remove_punctwithColumn通话。

另一种减少将 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM