scala - 如何将数据框列传递给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")
解决方案
您可以hoursToSeconds
使用以下 sytax 为该函数创建一个 udf:
val hoursToSecUdf = udf(hoursToSeconds _)
为了进一步在特定列上使用它,可以使用以下语法:
df.withColumn("TimeInSeconds",hoursToSecUdf(col("running")))
推荐阅读
- html - 导航栏切换器弄乱了导航栏品牌对齐
- database - 如何在 Go DRY 中扫描数据库行?
- abap - abap:从现有的一个创建动态内部表
- excel - 基于 2 个范围从每个单元格进行宏循环
- c++ - c++11 pugixml fpclassify() 警告 float-conversion from double to float 可能会改变它的值
- linux - 在子 makefile 中声明时,我的规则是不可见的
- python - Python 3.6 Conda 环境 Windows 10 中的 MatplotLib 问题
- javascript - 异步在运行前不等待函数
- jboss - 将 Wildfly 10 主页替换为包含在 ear 文件中的自定义应用程序
- powershell - 如果在 exe 中转换,Powershell 进度条不显示