簡體   English   中英

檢索行列值作為其Scala類型而不是列

[英]Retrieving Row column values as their Scala type and not Column

我想要實現的是在考慮到每一行的值的情況下,將值推斷為某些DataFrame列。

.withColumn("date", when(col("date").isNull, lit(new DateTime(col("timestamp").as[Long]).getYear)))

問題在於,我無法為每個Row對象檢索給定列的值。 我看過其他解決方案,但是它們要么列出所有行的整個值集,要么只是獲得它們的第一個值,這不是我要實現的目標。

像這樣的示例DF圖片...

 (year, val1, val2, val3, timestamp) (null, 10, 12, null, 123456789) (null, 11, 12, null, 234567897) 

在將單獨的功能(例如,從時間戳中提取年份)應用於每個行之后,我想看到的是...

 (year, val1, val2, val3, timestamp) (2018 [using DateTime class], 10, 12, 1012, 123456789) (2018 [using DateTime class], 12, 12, 1212, 234567897) 

有什么辦法嗎?

那就是UDF發揮作用的地方:

val udf_extractYear = udf((ts:Long) => new DateTime(ts).getYear)

那么你可以使用例如

df
.withColumn("year", when(col("year").isNull, udf_extractYear(col("timestamp"))).otherwise(col("year")))
.show()

如您所見,您的timestamp列自動映射到Long

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM