火花。将 Dataframe 传递给 pandas_udf 并返回一个系列

SAR*_*ose 1 python pandas apache-spark pyspark

我正在使用 PySpark 的新pandas_udf装饰器,我试图让它将多列作为输入并返回一个系列作为输入,但是,我得到了一个TypeError: Invalid argument

示例代码

@pandas_udf(df.schema, PandasUDFType.SCALAR)
def fun_function(df_in):
    df_in.loc[df_in['a'] < 0] = 0.0
    return (df_in['a'] - df_in['b']) / df_in['c']
Run Code Online (Sandbox Code Playgroud)

Psi*_*dom 5

A SCALAR udf expects pandas series as input instead of a data frame. For your case, there's no need to use a udf. Direct calculation from columns a, b, c after clipping should work:

import pyspark.sql.functions as f

df = spark.createDataFrame([[1,2,4],[-1,2,2]], ['a', 'b', 'c'])

clip = lambda x: f.when(df.a < 0, 0).otherwise(x)
df.withColumn('d', (clip(df.a) - clip(df.b)) / clip(df.c)).show()

#+---+---+---+-----+
#|  a|  b|  c|    d|
#+---+---+---+-----+
#|  1|  2|  4|-0.25|
#| -1|  2|  2| null|
#+---+---+---+-----+
Run Code Online (Sandbox Code Playgroud)

如果您必须使用 a pandas_udf,则您的返回类型必须是double,而不是df.schema因为您只返回一个熊猫系列而不是熊猫数据框;而且您还需要将列作为系列传递给函数而不是整个数据框:

@pandas_udf('double', PandasUDFType.SCALAR)
def fun_function(a, b, c):
    clip = lambda x: x.where(a >= 0, 0)
    return (clip(a) - clip(b)) / clip(c)

df.withColumn('d', fun_function(df.a, df.b, df.c)).show()
#+---+---+---+-----+                                                             
#|  a|  b|  c|    d|
#+---+---+---+-----+
#|  1|  2|  4|-0.25|
#| -1|  2|  2| null|
#+---+---+---+-----+
Run Code Online (Sandbox Code Playgroud)