上传列表以从火花数据框中选择多个列

Ben*_*Ben 47 apache-spark apache-spark-sql spark-dataframe

我有一个火花数据框df.有没有办法使用这些列的列表选择几列?

scala> df.columns
res0: Array[String] = Array("a", "b", "c", "d")
Run Code Online (Sandbox Code Playgroud)

我知道我可以做点什么df.select("b", "c").但是假设我有一个包含几个列名的列表val cols = List("b", "c"),有没有办法将它传递给df.select?df.select(cols)抛出错误.像df.select(*cols)python中的东西

Sha*_*ani 82

使用 df.select(cols.head, cols.tail: _*)

让我知道它是否有效:)

来自@Ben的解释:

关键是select的方法签名:

select(col: String, cols: String*)
Run Code Online (Sandbox Code Playgroud)

cols:String*条目采用可变数量的参数.:_*解包参数,以便可以通过此参数处理它们.非常类似于在python中解压缩*args.有关其他示例,请参见此处此处.

  • 我想我现在明白了.关键是select`select(col:String,cols:String*)`的方法签名.`cols:String*`条目采用可变数量的参数.`:_*`解包参数,以便它们可以被这个参数处理.非常类似于使用`*args`在python中解压缩.见[here](http://stackoverflow.com/a/1660768/4096199)和[here](http://stackoverflow.com/questions/6051302/what-does-colon-underscore-star-do-in-斯卡拉)其他例子. (13认同)

Ksh*_*tha 24

您可以将String类型转换为spark列,如下所示:

import org.apache.spark.sql.functions._
df.select(cols.map(col): _*)
Run Code Online (Sandbox Code Playgroud)


小智 21

我刚刚学到的另一种选择.

import org.apache.spark.sql.functions.col
val columns = Seq[String]("col1", "col2", "col3")
val colNames = columns.map(name => col(name))
val df = df.select(colNames:_*)
Run Code Online (Sandbox Code Playgroud)