繁体   English   中英

从数据帧 spark scala 中选择列数组和 expr

[英]select array of columns and expr from dataframe spark scala

我们可以从数据框中选择列列表和expr吗?

我需要从数据框中选择列列表和 expr。

下面是列列表

val dynamicColumnSelection = Array("a", "b", "c", "d", "e", "f")
// These columns will change dynamically.

而且我还有一个expr可以从同一个数据帧和上述列中进行选择。

expr("stack(3, 'g', g, 'h', h, 'i', i) as (Key,Value)") 

我可以选择列数组或单个列以及expr

df.select(col("a"), col("b"), col("c"), col("d"), col("e"),
          expr("stack(3, 'g', g, 'h', h, 'i', i) as (Key,Value)") )

但是这里dynamicColumnSelection列是动态准备的。

我们可以从数据框中选择列列表和expr吗?
请指导,我怎样才能做到这一点?

数据框很大,所以不寻找连接。

您可以做的是将列名数组转换为列数组,向其中添加表达式并使用:_*来“splat”生成的数组。

// simply creating a one line dataframe to check that it's working
val df = Seq((1, 2, 3, 4, 5 ,6, 7, 8, 9))
    .toDF("a", "b", "c", "d", "e", "f", "g", "h", "i")
val e = expr("stack(3, 'g', g, 'h', h, 'i', i) as (Key,Value)")
val dynamicColumnSelection = Array("a", "b", "c", "d", "e", "f")
val result = df.select(dynamicColumnSelection.map(col) :+ e :_*)
result.show()

哪个产量

+---+---+---+---+---+---+---+-----+
|  a|  b|  c|  d|  e|  f|Key|Value|
+---+---+---+---+---+---+---+-----+
|  1|  2|  3|  4|  5|  6|  g|    7|
|  1|  2|  3|  4|  5|  6|  h|    8|
|  1|  2|  3|  4|  5|  6|  i|    9|
+---+---+---+---+---+---+---+-----+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM