![](/img/trans.png)
[英]How can I add a column with a value to a new Dataset in Spark Java?
[英]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
但無法弄清楚如何實現這一點。
感謝任何幫助。
使用“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()
假設 DOB 是一個字符串,你可以編寫一個 UDF
def formatDate(s: String): String {
// date formatting code
}
val formatDateUdf = udf(formatDate(_: String))
ds.select($"NAME", formatDateUdf($"DOB").as("DOB"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.