簡體   English   中英

嘗試通過數據框在Pyspark中執行用戶定義的函數時出錯

[英]Error when trying to execute User Defined Functions in Pyspark over a Dataframe

我正在Pyspark中創建一個小程序,我想在其中生成一個Used Defined Function,以將lambda函數中的method1調用為method0。

為了簡化理解,我簡化了代碼,但是核心功能是:對於數據幀中的每個實例,“ method0”應用“ method1”(借助lambda函數)以根據正在檢查的實例。 這樣,如果滿足“方法1”的第一個條件,則該實例的值應為“-”,但如果不滿足,則應為“其他”。

通過這些操作,我們的想法是從該UDF獲取一列並將其附加到“ method0”中的數據幀。 這是修改后的代碼,可讓您更容易理解:

def method1(atr_list, instance, ident):

    if(instance.ATR1 != '-'):
        return instance.ATR1
    else:
        # Other operations ...
        return 'other'

def method0(df, atr_example_list, ident):

    udf_func = udf(lambda instance: method1(atr_example_list, instance, ident), returnType=StringType())
    new_column = udf_func(df)
    df = df.withColumnRenamed("New_Column", new_column)
    return df

result = method0(df, list, "1111")

但是,當我執行此代碼時,會收到下一個錯誤,我真的不知道為什么:

Py4JError: An error occurred while calling o298.__getnewargs__. Trace:
py4j.Py4JException: Method __getnewargs__([]) does not exist
at 
py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
at 
py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
at py4j.Gateway.invoke(Gateway.java:272)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:214)
at java.lang.Thread.run(Thread.java:748)

這是我期望的輸入和輸出示例:

數據框“ df”:

+-------+-------+-------+
| ATR1  |  ATR2 | ATRN  |
+-------+-------+-------+
| '-'   |   1   |  'a'  |
| '-'   |   1   |  'a'  |
| '-'   |   2   |  'b'  | 
| '++'  |   1   |  'a'  |
+-------+-------+-------+

將數據框“ df”作為參數傳遞給“ method0”(對於此簡化示例,不必查看參數“ atr_example_list”和“ ident”),我想在“ method1”調用中獲得像這樣的列:

+------------+
| new_column |
+------------+
|   'other'  |
|   'other'  |
|   'other'  |
|    '++'    |
+------------+

因此在method0上,新的數據幀將是:

+-------+-------+-------+------------+
| ATR1  |  ATR2 | ATRN  | new_column |
+-------+-------+-------+------------+
| '-'   |   1   |  'a'  |   'other'  |
| '-'   |   1   |  'a'  |   'other'  |
| '-'   |   2   |  'b'  |   'other'  | 
| '++'  |   1   |  'a'  |    '++'    |
+-------+-------+-------+------------+

有人可以幫我嗎?

您不能像這樣簡化和使用單個udf(如果需要,method1可以占用多個列)?

def method1(x):
  if x != "-":
    return x
  else:
    return 'other'

u_method1 = udf(method1, StringType())

result = df.withColumn("new_column", u_method1("ATR1"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM