2016-05-20 11 views
5

ho un dataframe chiamato train, ha il seguente schema:stringa Converti in timestamp per Spark usando Scala

root 
|-- date_time: string (nullable = true) 
|-- site_name: integer (nullable = true) 
|-- posa_continent: integer (nullable = true) 

voglio lanciare la colonna date_time-timestamp e creare una nuova colonna con il valore year estratto dalla colonna date_time.

Per essere chiari, ho il seguente dataframe:

+-------------------+---------+--------------+ 
|   date_time|site_name|posa_continent| 
+-------------------+---------+--------------+ 
|2014-08-11 07:46:59|  2|    3| 
|2014-08-11 08:22:12|  2|    3| 
|2015-08-11 08:24:33|  2|    3| 
|2016-08-09 18:05:16|  2|    3| 
|2011-08-09 18:08:18|  2|    3| 
|2009-08-09 18:13:12|  2|    3| 
|2014-07-16 09:42:23|  2|    3| 
+-------------------+---------+--------------+ 

voglio ottenere le seguenti dataframe:

+-------------------+---------+--------------+--------+ 
|   date_time|site_name|posa_continent|year | 
+-------------------+---------+--------------+--------+ 
|2014-08-11 07:46:59|  2|    3|2014 | 
|2014-08-11 08:22:12|  2|    3|2014 | 
|2015-08-11 08:24:33|  2|    3|2015 | 
|2016-08-09 18:05:16|  2|    3|2016 | 
|2011-08-09 18:08:18|  2|    3|2011 | 
|2009-08-09 18:13:12|  2|    3|2009 | 
|2014-07-16 09:42:23|  2|    3|2014 | 
+-------------------+---------+--------------+--------+ 

risposta

10

Beh, se si vuole cast del date_timecolumn a timestampand creare un nuova colonna con il valore dell'anno quindi fare esattamente questo:

import org.apache.spark.sql.functions.year 

df 
    .withColumn("date_time", $"date_time".cast("timestamp")) // cast to timestamp 
    .withColumn("year", year($"date_time")) // add year column 
+0

@jackAKAkarthik Questa non è la stessa cosa, e sembra il codice non riesce con un po 'di lavoro in streaming. – zero323

+0

Fallisce solo dopo aver aggiunto .withColumn al mio dataframe. –

+0

Quindi wat può essere il problema qui? –

1

Si potrebbe mappa del dataframe per aggiungere l'anno alla fine di ogni riga:

df.map { 
    case Row(col1: String, col2: Int, col3: Int) => (col1, col2, col3, DateTime.parse(col1, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).getYear) 
}.toDF("date_time", "site_name", "posa_continent", "year").show()