Scala:可变 UDF

Scala: variadic UDF

我有一个包含很多列的 DataFrame。 我还有一个功能

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

这相当复杂,但需要一些字符串和 returns 一个 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: Unsupported literal type class scala.runtime.BoxedUnit ()

如何向DF申请函数?

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

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

来自val cols = getColsToEncode()

val cols = getColsToEncode

直接将函数传入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))