Scala:可变UDF

时间:2016-10-28 14:19:23

标签: scala udf

我有一个包含许多列的DataFrame。 我也有一个功能

def getFeatureVector(features:Array[String]) : Vector

这相当复杂,但需要一些字符串并返回一个spark MLlib向量。

现在,我想查看DF中的一些列(我事先不知道哪些列),将它们传递给getFeatureVector,然后添加一个包含结果向量的新列。

我可以访问我想要使用的列数组,并且我编写了一个将其强制转换为字符串的函数,并创建了一个数组列:

val colNamesToEncode = Array("col1", "col2", "col3", "col4")
def getColsToEncode:Column = {
    val cols = colNamesToEncode.map(x => col(x).cast("string"))
    array(cols:_*)
}

最后,我尝试制作一个udf并将其应用于DF:

val encoderUDF = udf(getFeatureVector _)
val cols = getColsToEncode()
data.withColumn(featuresColName,encoderUDF(cols))

但是当我运行它时,我得到java.lang.RuntimeException:不支持的文字类型类scala.runtime.BoxedUnit()

如何将功能应用于DF?

PS:我在编写代码时使用了这个答案(Spark UDF with varargs)作为指南。

2 个答案:

答案 0 :(得分:0)

只需从以下行中删除()即可解决错误。

来自val cols = getColsToEncode()

val cols = getColsToEncode

答案 1 :(得分:0)

您可以直接将该函数传递给udf函数。

val colNamesToEncode = Array("col1", "col2", "col3", "col4")
def getColsToEncode:Column = {
val cols = colNamesToEncode.map(x => col(x).cast("string"))
array(cols:_*)
}

val encoderUDF = udf(getFeatureVector _)
data.withColumn(featuresColName,encoderUDF(getColsToEncode))