【问题标题】:How to pass a dataframe column to scala function如何将数据框列传递给scala函数
【发布时间】:2020-02-25 06:34:34
【问题描述】:

我编写了一个 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 方法的数据框列之一(运行),但出现错误类型不匹配,预期:列,实际字符串。任何帮助将不胜感激,有没有办法可以将 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")

【问题讨论】:

    标签: scala apache-spark user-defined-functions


    【解决方案1】:

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

    val hoursToSecUdf = udf(hoursToSeconds _)
    

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    相关资源
    最近更新 更多