使用Spark 2.x我正在使用数据帧。
val proposals = spark.read
.option("header", true)
.option("inferSchema", true)
.option("delimiter", ";")
.csv("/proposals.txt.gz")
proposals.printSchema()
工作正常并给出:
root
|-- MARKETCODE: string (nullable = true)
|-- REFDATE: string (nullable = true)
|-- UPDTIME: string (nullable = true)
|-- UPDTIMEMSEC: integer (nullable = true)
|-- ENDTIME: string (nullable = true)
|-- ENDTIMEMSEC: integer (nullable = true)
|-- BONDCODE: string (nullable = true)
现在我想用毫秒计算一个时间,因此编写了一个函数:
def time2usecs( time:String, msec:Int )={
val Array(hour,minute,seconds) = time.split(":").map( _.toInt )
msec + seconds.toInt*1000 + minute.toInt*60*1000 + hour.toInt*60*60*1000
}
time2usecs( "08:13:44", 111 )
time2usecs: (time: String, msec: Int)Int
res90: Int = 29624111
这个谜题的最后一个平静点是:
proposals.withColumn( "utime",
proposals.select("UPDTIME","UPDTIMEMSEC")
.map( (t,tms) => time2usecs(t,tms) ))
但我无法弄清楚如何做df.select(column1, column2).map(...)
部分。
答案 0 :(得分:3)
在Spark中对数据帧列使用方法的常用方法是定义UDF
(用户定义函数,有关详细信息,请参阅here)。对于你的情况:
import org.apache.spark.sql.functions.udf
import spark.implicits._
val time2usecs = udf((time: String, msec: Int) => {
val Array(hour,minute,seconds) = time.split(":").map( _.toInt )
msec + seconds.toInt*1000 + minute.toInt*60*1000 + hour.toInt*60*60*1000
})
val df2 = df.withColumn("utime", time2usecs($"UPDTIME", $"UPDTIMEMSEC"))
此处导入 spark.implicits._
,以允许$
功能使用col()
简写。
答案 1 :(得分:2)
为什么不一直使用SQL?
import org.apache.spark.sql.Column
import org.apache.spark.sql.functions._
def time2usecs(time: Column, msec: Column) = {
val bits = split(time, ":")
msec + bits(2).cast("int") * 1000 + bits(1).cast("int") * 60 * 1000 +
bits(0).cast("int") *60*60*1000
}
df.withColumn("ts", time2usecs(col(""UPDTIME"), col("UPDTIMEMSEC"))
使用您的代码,您必须:
proposals
.select("UPDTIME","UPDTIMEMSEC")
.as[(String, Int)]
.map { case (t, s) => time2usecs(t, s) }