Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用两个变量列表添加scala列_Scala_Apache Spark_Apache Spark Sql - Fatal编程技术网

使用两个变量列表添加scala列

使用两个变量列表添加scala列,scala,apache-spark,apache-spark-sql,Scala,Apache Spark,Apache Spark Sql,我有两个seq,我想用来向数据帧添加列 Seq one类似于: Seq(“红色”、“蓝色”、“绿色”、“黄色”、“紫色”) 下面的第二个是: Seq(“儿童”、“青少年”、“成人”、“老年人”) 我还有一个列,它是一个字符串,格式为:s“$color+$age score=$score”,包含颜色和年龄的每一个组合,以及结果分数,因此有20个不同的颜色年龄分数 目前,我正在做类似的事情 finalDF.withColumn("red_child", getScore("red", "child"

我有两个seq,我想用来向数据帧添加列

Seq one类似于:
Seq(“红色”、“蓝色”、“绿色”、“黄色”、“紫色”)

下面的第二个是:
Seq(“儿童”、“青少年”、“成人”、“老年人”)

我还有一个列,它是一个字符串,格式为:s“$color+$age score=$score”,包含颜色和年龄的每一个组合,以及结果分数,因此有20个不同的颜色年龄分数

目前,我正在做类似的事情

finalDF.withColumn("red_child", getScore("red", "child"))
.withColumn("red_teen", getScore("red", "teen"))
.withColumn("red_adult", getScore("red", "adult"))
以此类推,对于所有20种可能的组合,getScore是一个处理regex的助手函数

因为我使用withColumn 20次,所以代码很难阅读。我想知道是否有任何方法可以使这段代码看起来更干净,使用两个seq for color和age循环并将列添加到数据帧中


谢谢。

您可以简单地
选择
从使用
生成的元组列表中派生的附加列,以便理解
,如下所示:

val colors = Seq("red", "blue", "green", "yellow", "violet")
val ageGroups = Seq("child", "teen", "adult", "senior")

val colPairs = for { c <- colors; a <- ageGroups } yield (c, a)

def getScore(c: String, a: String): Column = ???

df.select( df.columns.map(col) ++ colPairs.map{ case (c, a) =>
    getScore(c, a).as(c + "_" + a)
  }: _*
)
colPairs.foldLeft(df){ case (accDF, (c, a)) =>
  accDF.withColumn(c + "_" + a, getScore(c, a))
}