首页 > 解决方案 > 如何将数据框列传递给scala函数

问题描述

我编写了一个 scala 函数,它将时间(HH:mm:ss.SSS)转换为秒。首先它将忽略毫秒并且只需要(HH:mm:ss)并转换为秒(int)。在 spark-shell 中测试时效果很好。

def hoursToSeconds(a: Any): Int = {
 val sec = a.toString.split('.')
 val fields = sec(0).split(':')
 val creationSeconds = fields(0).toInt*3600 + fields(1).toInt*60 + fields(2).toInt
 return creationSeconds
}

print(hoursToSeconds("03:51:21.2550000"))
13881

我需要将此函数传递给我正在尝试使用 withColumn 方法的数据框列之一(运行),但出现错误Type mismatch, expected: column, actual String。任何帮助将不胜感激,有没有办法可以将 scala 函数传递给 udf,然后在 df.withColumn 中使用 udf。

df.printSchema
root
 |-- vin: string (nullable = true)
 |-- BeginOfDay: string (nullable = true)
 |-- Timezone: string (nullable = true)
 |-- Version: timestamp (nullable = true)
 |-- Running: string (nullable = true)
 |-- Idling: string (nullable = true)
 |-- Stopped: string (nullable = true)
 |-- dlLoadDate: string (nullable = false)

示例运行列值。

在此处输入图像描述

df.withColumn("running", hoursToSeconds(df("Running")

标签: scalaapache-sparkuser-defined-functions

解决方案


您可以hoursToSeconds使用以下 sytax 为该函数创建一个 udf:

val hoursToSecUdf = udf(hoursToSeconds _)

为了进一步在特定列上使用它,可以使用以下语法:

df.withColumn("TimeInSeconds",hoursToSecUdf(col("running")))

推荐阅读