我想拆分包含日期时间的列“_time”(作为 fieldtype = string)
“_time”列中的日期如下所示:27-11-2017 08:20:33 所以我认为这可行:
df.withColumn("col1", split(col("_time"), "\\-").getItem(0))
.withColumn("col2", split(col("_time"), "\\-").getItem(1))
.withColumn("col3", split(col("_time"), "\\-").getItem(2))
.withColumn("col4", split(col("_time"), "\\' '").getItem(3))
.show()
但这会导致:
-------------------+----+----+-------------+----+
_time|col1|col2| col3|col4|
-------------------+----+----+-------------+----+
27-11-2017 08:20:33| 27| 11|2017 08:20:33|null|
27-11-2017 08:20:35| 27| 11|2017 08:20:35|null|
27-11-2017 08:20:35| 27| 11|2017 08:20:35|null|
所以,它似乎对空间没有任何作用。我尝试过使用这个:
.withColumn("col4", split(col("_time"), "\\' '")
但这也行不通。 (给出相同的结果)
有什么建议吗?
问候
最佳答案
在 split
方法中使用 |
(在正则表达式中表示“或”)来指示 -
或 whitespace
可以是分隔符,如下所示:
val df = Seq(
"27-11-2017 08:20:33", "28-12-2017 09:30:44"
).toDF("_time")
df.
withColumn("tsArr", split($"_time", "\\-|\\s")).
select($"tsArr"(0), $"tsArr"(1), $"tsArr"(2), $"tsArr"(3)).
show
// +--------+--------+--------+--------+
// |tsArr[0]|tsArr[1]|tsArr[2]|tsArr[3]|
// +--------+--------+--------+--------+
// | 27| 11| 2017|08:20:33|
// | 28| 12| 2017|09:30:44|
// +--------+--------+--------+--------+
关于scala - 如何使用scala根据一个字符和一个空格分割一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734794/