StuffHappens
StuffHappens

Reputation: 6557

Pyspark pass function as a parameter to UDF

I'm trying to create a UDF which takes another function as a parameter. But the execution ends up with an exception. The code I run:

import pandas as pd
from pyspark import SparkConf, SparkContext, SQLContext
from pyspark.sql.types import MapType, DataType, StringType
from pyspark.sql.functions import udf, struct, lit
import os

sc = SparkContext.getOrCreate(conf=conf)
sqlContext = SQLContext(sc)

df_to_test = sqlContext.createDataFrame(
    pd.DataFrame({
        'inn': ['111', '222', '333'],
        'field1': [1, 2, 3],
        'field2': ['a', 'b', 'c']
    }))

def foo_fun(row, b) -> str:
    return 'a' + b()

def bar_fun():
    return 'I am bar'

foo_fun_udf = udf(foo_fun, StringType())
df_to_test.withColumn(
    'foo', 
    foo_fun_udf(struct([df_to_test[x] for x in df_to_test.columns]), bar_fun)
).show()

The exception:

Invalid argument, not a string or column: <function bar_fun at 0x7f0e69ce6268> of type <class 'function'>. For column literals, use 'lit', 'array', 'struct' or 'create_map' function.

I tried to wrap bar_fun into udf with no success. Is there a way to pass function as a parameter?

Upvotes: 1

Views: 1864

Answers (1)

Steven
Steven

Reputation: 15293

You are not so far from the solution. Here is how I would do it :

def foo_fun_udf(func):

    def foo_fun(row) -> str:
        return 'a' + func()

    out_udf = udf(foo_fun, StringType())
    return out_udf 

df_to_test.withColumn(
    'foo', 
    foo_fun_udf(bar_fun)(struct([df_to_test[x] for x in df_to_test.columns]))
).show()

Upvotes: 1

Related Questions