如何在spark scala

时间:2018-04-30 18:00:32

标签: scala apache-spark spark-dataframe

这可能是火花scala吗?我正在使用spark 2.2

val func="""withColumn("seq", lit("this is seq"))
           .withColumn("id", lit("this is id"))
           .withColumn("type", lit("this is type"))"""

然后在数据帧(df)之上使用上面的变量,就像这样

val df2=df.$func

我将这些函数保存到变量的原因是我想根据条件动态应用函数。有时我可能想要1 withColumn,有时我可能需要多个withColumn函数。

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您可以使用foldLeft

执行此操作

假设您有dataframe df为

val df: DataFrame = Seq(("123"), ("123"), ("223"), ("223")).toDF()

您可以创建list列名称和您称为

的操作/功能
val list = List(
  ("seq", lit("this is seq")),
  ("id", lit("this is id")),
  ("type" , lit("thisis type"))
)

现在您可以使用foldLeft将此列表用作

list.foldLeft(df){(tempDF, listValue) =>
  tempDF.withColumn(listValue._1, listValue._2)
}

最终结果:

+-----+-----------+----------+-----------+
|value|seq        |id        |type       |
+-----+-----------+----------+-----------+
|123  |this is seq|this is id|thisis type|
|123  |this is seq|this is id|thisis type|
|223  |this is seq|this is id|thisis type|
|223  |this is seq|this is id|thisis type|
+-----+-----------+----------+-----------+

希望这有帮助!