[英]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.