[英]Scala - Spark - How to transform a dataframe containing one string column to a DF with columns with the rigth type?
[英]Spark Scala: How to transform a column in a DF
我在Spark中有一个数据框,有很多列和我定义的udf。 我希望返回相同的数据帧,除非转换了一列。 此外,我的udf接受一个字符串并返回一个时间戳。 是否有捷径可寻? 我试过了
val test = myDF.select("my_column").rdd.map(r => getTimestamp(r))
但这会返回一个RDD,只返回已转换的列。
如果你真的需要使用你的功能,我可以建议两个选项:
1)使用map / toDF:
import org.apache.spark.sql.Row
import sqlContext.implicits._
def getTimestamp: (String => java.sql.Timestamp) = // your function here
val test = myDF.select("my_column").rdd.map {
case Row(string_val: String) => (string_val, getTimestamp(string_val))
}.toDF("my_column", "new_column")
2)使用UDF( UserDefinedFunction
):
import org.apache.spark.sql.functions._
def getTimestamp: (String => java.sql.Timestamp) = // your function here
val newCol = udf(getTimestamp).apply(col("my_column")) // creates the new column
val test = myDF.withColumn("new_column", newCol) // adds the new column to original DF
Bill Chambers在这篇很好的文章中有关于Spark SQL UDF的更多细节。
或者 ,
如果您只想将StringType
列转换为TimestampType
列,则可以使用自Spark SQL 1.5以来可用的unix_timestamp
列函数 :
val test = myDF
.withColumn("new_column", unix_timestamp(col("my_column"), "yyyy-MM-dd HH:mm").cast("timestamp"))
注意:对于spark 1.5.x,必须在转换为timestamp之前将unix_timestamp
的结果乘以1000
(发出SPARK-11724 )。 结果代码将是:
val test = myDF
.withColumn("new_column", (unix_timestamp(col("my_column"), "yyyy-MM-dd HH:mm") *1000L).cast("timestamp"))
编辑:添加了udf选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.