[英]How to dynamically build column name in spark sql withColumn
您可以從國家列表中鏈接多個when
表達式:
val countries = Seq("us", "uk", "ind")
val expCol = countries.foldLeft(lit(null)) { case (acc, country) =>
when(col("country")===country, col(s"exp_$country")).otherwise(acc)
}
val df1 = df.withColumn("exp", expCol)
或者,如果您更喜歡從exp_*
列創建 map 表達式country -> exp
,而不是使用 map 創建exp
列:
val mapCountries = map(
df.columns
.filter(_.startsWith("exp_"))
.flatMap(c => Seq(lit(c.split("_")(1)), col(c))): _*
)
val df1 = df.withColumn("exp", mapCountries(col("country")))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.