如何在spark sql withColumn中动态构建列名

How to dynamically build column name in spark sql withColumn

我有如下示例数据。

我想根据 country 字段值填充另一列 exp

类似下面的内容

df.withColumn("exp",col(s"exp_$country"))

所以相应的 country 号码可以放在那里。

但是上面的代码出错了:

cannot resolve country

我需要的输出是

感谢任何帮助。

您可以从国家列表中链接多个 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_* 创建地图表达式 country -> exp 而不是使用地图创建 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")))