gpt4 book ai didi

scala - 基于现有列在 DataFrame 中添加新列

转载 作者:行者123 更新时间:2023-12-01 09:55:04 24 4
gpt4 key购买 nike

我有一个包含日期时间列的 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")))

callUDFcol 包含在functions 中作为import 显示

col("dt_string") 中的 dt_string 是您要从中转换的 df 的原始列名称。

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

val dtFunc2 = udf(dtFunc)
val x = df.withColumn("dt", dtFunc2(col("dt_string")))

关于scala - 基于现有列在 DataFrame 中添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29909448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com