在现有列的DataFrame中添加新列

use*_*513 3 scala apache-spark apache-spark-sql

我有一个带有datetime列的csv文件:"2011-05-02T04:52:09 + 00:00".

我正在使用scala,文件被加载到spark DataFrame中,我可以使用jodas时间来解析日期:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
val df = new SQLContext(sc).load("com.databricks.spark.csv", Map("path" -> "data.csv", "header" -> "true")) 
val d = org.joda.time.format.DateTimeFormat.forPattern("yyyy-mm-dd'T'kk:mm:ssZ")
Run Code Online (Sandbox Code Playgroud)

我想基于datetime字段创建新列以进行时间序列分析.

在DataFrame中,如何根据另一列的值创建列?

我注意到DataFrame具有以下功能:df.withColumn("dt",column),有没有办法根据现有列的值创建列?

谢谢

yjs*_*hen 7

import org.apache.spark.sql.types.DateType
import org.apache.spark.sql.functions._
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat

val d = DateTimeFormat.forPattern("yyyy-mm-dd'T'kk:mm:ssZ")
val dtFunc: (String => Date) = (arg1: String) => DateTime.parse(arg1, d).toDate
val x = df.withColumn("dt", callUDF(dtFunc, DateType, col("dt_string")))
Run Code Online (Sandbox Code Playgroud)

callUDF,col包括在functions作为import表演

dt_string里面col("dt_string")是你的自由度,这要从转变的起源列名.

或者,您可以将最后一个语句替换为:

val dtFunc2 = udf(dtFunc)
val x = df.withColumn("dt", dtFunc2(col("dt_string")))
Run Code Online (Sandbox Code Playgroud)