Spark(Scala)在for循环内执行数据框 [英] Spark (Scala) execute dataframe within for loop
本文介绍了Spark(Scala)在for循环内执行数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用spark 1.6.1版本.我需要循环执行数据框.
I am using spark 1.6.1 version. I have requirement to execute dataframe in loop.
for ( i <- List ('a','b')){
val i = sqlContext.sql("SELECT i, col1, col2 FROM DF1")}
我希望此数据帧执行两次(i = a
和i = b
).
I want this dataframe to be executed twice (i = a
and i = b
).
推荐答案
您的代码几乎正确. 除了两件事:
Your code is almost correct. Except two things :
-
i
已在您的for
循环中使用,因此请不要在val i =
中使用它
- 如果要在字符串中使用
i
的值,请使用字符串插值"
i
is already used in yourfor
loop so don't use it inval i =
- If you want to use the value of
i
in a string, use String Interpolation
因此您的代码应类似于:
So your code should look like :
for (i <- List ('a','b')) {
val df = sqlContext.sql(s"SELECT $i, col1, col2 FROM DF1")
df.show()
}
作者评论后
您可以先使用.map
然后使用.reduceLeft
来完成此操作:
You can do this with a .map
and then a .reduceLeft
:
// All your dataframes
val dfs = Seq('a','b').map { i =>
sqlContext.sql(s"SELECT $i, col1, col2 FROM DF1")
}
// Then you can reduce your dataframes into one
val unionDF = dfs.reduceLeft((dfa, dfb) =>
dfa.unionAll(dfb)
)
这篇关于Spark(Scala)在for循环内执行数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文