【发布时间】:2016-11-04 23:24:09
【问题描述】:
Spark Version: spark-2.0.1-bin-hadoop2.7
Scala: 2.11.8
我正在将原始 csv 加载到 DataFrame 中。在 csv 中,虽然该列支持日期格式,但它们被写为 20161025 而不是 2016-10-25。参数date_format包含需要转换为yyyy-mm-dd格式的列名字符串。
在下面的代码中,我首先通过schema将Date列的csv加载为StringType,然后检查date_format是否不为空,即有需要转换为@987654325的列@ 来自String,然后使用unix_timestamp 和to_date 转换每一列。但是在csv_df.show()中,返回的行都是null。
def read_csv(csv_source:String, delimiter:String, is_first_line_header:Boolean,
schema:StructType, date_format:List[String]): DataFrame = {
println("|||| Reading CSV Input ||||")
var csv_df = sqlContext.read
.format("com.databricks.spark.csv")
.schema(schema)
.option("header", is_first_line_header)
.option("delimiter", delimiter)
.load(csv_source)
println("|||| Successfully read CSV. Number of rows -> " + csv_df.count() + " ||||")
if(date_format.length > 0) {
for (i <- 0 until date_format.length) {
csv_df = csv_df.select(to_date(unix_timestamp(
csv_df(date_format(i)), "yyyy-MM-dd").cast("timestamp")))
csv_df.show()
}
}
csv_df
}
返回前 20 行:
+-------------------------------------------------------------------------+
|to_date(CAST(unix_timestamp(prom_price_date, YYYY-MM-DD) AS TIMESTAMP))|
+-------------------------------------------------------------------------+
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
| null|
+-------------------------------------------------------------------------+
为什么我得到所有null?
【问题讨论】:
标签: scala apache-spark apache-spark-sql spark-dataframe spark-csv