Spark Dataset - 如何通过修改现有列值来创建新列
Spark Dataset - How to create a new column by modifying an existing column value
我有如下数据集
Dataset<Row> dataset = ...
dataset.show()
| NAME | DOB |
+------+----------+
| John | 19801012 |
| Mark | 19760502 |
| Mick | 19911208 |
我想将其转换为以下格式(格式为 DOB)
| NAME | DOB |
+------+------------+
| John | 1980-10-12 |
| Mark | 1976-05-02 |
| Mick | 1991-12-08 |
我该怎么做?基本上,我试图找出如何以通用方式操作现有列字符串值。
我试过使用 dataset.withColumn
但不太明白如何实现。
感谢任何帮助。
假设 DOB 是一个字符串,您可以编写一个 UDF
def formatDate(s: String): String {
// date formatting code
}
val formatDateUdf = udf(formatDate(_: String))
ds.select($"NAME", formatDateUdf($"DOB").as("DOB"))
使用 "substring" 和 "concat" 函数:
df.withColumn("DOB_FORMATED",
concat(substring($"DOB", 0, 4), lit("-"), substring($"DOB", 5, 2), lit("-"), substring($"DOB", 7, 2)))
将数据加载到数据帧(deltaData)中,只需使用以下行
deltaData.withColumn("DOB", date_format(to_date($"DOB", "yyyyMMdd"), "yyyy-MM-dd")).show()
我有如下数据集
Dataset<Row> dataset = ...
dataset.show()
| NAME | DOB |
+------+----------+
| John | 19801012 |
| Mark | 19760502 |
| Mick | 19911208 |
我想将其转换为以下格式(格式为 DOB)
| NAME | DOB |
+------+------------+
| John | 1980-10-12 |
| Mark | 1976-05-02 |
| Mick | 1991-12-08 |
我该怎么做?基本上,我试图找出如何以通用方式操作现有列字符串值。
我试过使用 dataset.withColumn
但不太明白如何实现。
感谢任何帮助。
假设 DOB 是一个字符串,您可以编写一个 UDF
def formatDate(s: String): String {
// date formatting code
}
val formatDateUdf = udf(formatDate(_: String))
ds.select($"NAME", formatDateUdf($"DOB").as("DOB"))
使用 "substring" 和 "concat" 函数:
df.withColumn("DOB_FORMATED",
concat(substring($"DOB", 0, 4), lit("-"), substring($"DOB", 5, 2), lit("-"), substring($"DOB", 7, 2)))
将数据加载到数据帧(deltaData)中,只需使用以下行
deltaData.withColumn("DOB", date_format(to_date($"DOB", "yyyyMMdd"), "yyyy-MM-dd")).show()