2017-10-30 9 views
-1

私はunixtimestampでデータフレームに列を持ち、それを列(年、月、日、時間)に変換して同じデータフレームに追加したいと考えています。unixtimestampからdate time inscalaへの変換

time 
----------- 
1462680000 
1462683600 
1462687200 

答えて

1

出典DF:

scala> df.show 
+---+----------+ 
| id|  time| 
+---+----------+ 
| 1| 462680000| 
| 2|1462683600| 
| 3|1462687200| 
+---+----------+ 

ソリューション:

scala> import org.apache.spark.sql.functions._ 

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

val df2 = df.withColumn("year", year(from_unixtime(df("time")))) 
      .withColumn("month", month(from_unixtime(df("time")))) 
      .withColumn("day", dayofmonth(from_unixtime(df("time")))) 
      .withColumn("tm", date_format(from_unixtime(df("time")),"HH:MM:SS")) 

// Exiting paste mode, now interpreting. 

df2: org.apache.spark.sql.DataFrame = [id: int, time: int ... 4 more fields] 

scala> df2.show 
+---+----------+----+-----+---+--------+ 
| id|  time|year|month|day|  tm| 
+---+----------+----+-----+---+--------+ 
| 1| 462680000|1984| 8| 30|04:08:00| 
| 2|1462683600|2016| 5| 8|07:05:00| 
| 3|1462687200|2016| 5| 8|08:05:00| 
+---+----------+----+-----+---+--------+ 

scala> df2.printSchema 
root 
|-- id: integer (nullable = true) 
|-- time: integer (nullable = true) 
|-- year: integer (nullable = true) 
|-- month: integer (nullable = true) 
|-- day: integer (nullable = true) 
|-- tm: string (nullable = true) 
0

このような操作と同様の函数の多くは、ベストプラクティスがにあるorg.apache.spark.sql.functionsパッケージ

で見つけることができ時間など文字列コレクション、...で動作しますColumnの変換が必要なときはいつでもそのパッケージを見てください。それらを使用すると、自分自身を定義することと比べて多くの最適化が得られるからですUDF

私はunixtimestampとデータフレームの列を持っていると私は列(年、月、日、時間)に変換し、同じデータフレームに追加する:あなたの具体的な質問について。

次のコードは、作業実行する必要があります。

import org.apache.spark.sql.functions._ 
val extractedDf = df.withColumn("day", year("column"), month("column"), dayofmonth("column")) 
関連する問題