基于现有列在 DataFrame 中添加新列
Add new column in DataFrame base on existing column
我有一个包含日期时间列的 csv 文件:“2011-05-02T04:52:09+00:00”。
我正在使用 scala,文件已加载到 spark DataFrame 中,我可以使用 jodas time 来解析日期:
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")
我想基于日期时间字段创建新列以进行时间序列分析。
在 DataFrame 中,如何根据另一列的值创建一个列?
我注意到 DataFrame 具有以下功能:df.withColumn("dt",column),有没有办法根据现有列的值创建列?
谢谢
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")))
callUDF
、col
作为import
显示
包含在functions
中
col("dt_string")
里面的dt_string
是你要转换的df的原始列名。
或者,您可以将最后一条语句替换为:
val dtFunc2 = udf(dtFunc)
val x = df.withColumn("dt", dtFunc2(col("dt_string")))
我有一个包含日期时间列的 csv 文件:“2011-05-02T04:52:09+00:00”。
我正在使用 scala,文件已加载到 spark DataFrame 中,我可以使用 jodas time 来解析日期:
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")
我想基于日期时间字段创建新列以进行时间序列分析。
在 DataFrame 中,如何根据另一列的值创建一个列?
我注意到 DataFrame 具有以下功能:df.withColumn("dt",column),有没有办法根据现有列的值创建列?
谢谢
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")))
callUDF
、col
作为import
显示
functions
中
col("dt_string")
里面的dt_string
是你要转换的df的原始列名。
或者,您可以将最后一条语句替换为:
val dtFunc2 = udf(dtFunc)
val x = df.withColumn("dt", dtFunc2(col("dt_string")))