scala 获取Spark数据框列列表

fcg9iug3  于 2022-11-09  发布在  Scala
关注(0)|答案(5)|浏览(167)

如何将Spark Dataframe 中的所有列名都放到一个Seq变量中。
输入数据和架构

val dataset1 = Seq(("66", "a", "4"), ("67", "a", "0"), ("70", "b", "4"), ("71", "d", "4")).toDF("KEY1", "KEY2", "ID")

dataset1.printSchema()
root
|-- KEY1: string (nullable = true)
|-- KEY2: string (nullable = true)
|-- ID: string (nullable = true)

我需要使用Scala编程将所有列名存储在变量中。我试过了,如下所示,但不起作用。

val selectColumns = dataset1.schema.fields.toSeq

selectColumns: Seq[org.apache.spark.sql.types.StructField] = WrappedArray(StructField(KEY1,StringType,true),StructField(KEY2,StringType,true),StructField(ID,StringType,true))

预期产出:

val selectColumns = Seq(
  col("KEY1"),
  col("KEY2"),
  col("ID")
)

selectColumns: Seq[org.apache.spark.sql.Column] = List(KEY1, KEY2, ID)
lb3vh1jj

lb3vh1jj1#

您可以使用以下命令:

val selectColumns = dataset1.columns.toSeq
scala> val dataset1 = Seq(("66", "a", "4"), ("67", "a", "0"), ("70", "b", "4"), ("71", "d", "4")).toDF("KEY1", "KEY2", "ID")
dataset1: org.apache.spark.sql.DataFrame = [KEY1: string, KEY2: string ... 1 more field]

scala> val selectColumns = dataset1.columns.toSeq
selectColumns: Seq[String] = WrappedArray(KEY1, KEY2, ID)
kq4fsx7k

kq4fsx7k2#

val selectColumns = dataset1.columns.toList.map(col(_))
67up9zun

67up9zun3#

我按如下方式使用Columns属性

val cols = dataset1.columns.toSeq

然后,如果您稍后要按从头到尾的顺序选择所有列,则可以使用

val orderedDF = dataset1.select(cols.head, cols.tail:_ *)
eqzww0vc

eqzww0vc4#

我们可以通过以下方式将数据集/表的列名获取到序列变量中。
从数据集中,

val col_seq:Seq[String] = dataset.columns.toSeq

从table上,

val col_seq:Seq[String] = spark.table("tablename").columns.toSeq
                           or
val col_seq:Seq[String] = spark.catalog.listColumns("tablename").select('name).collect.map(col=>col.toString).toSeq
mm9b1k5b

mm9b1k5b5#

这些列也可以从模式中提取。

val dataset1 = Seq(("66", "a", "4"), ("67", "a", "0"), ("70", "b", "4"), ("71", "d", "4")).toDF("KEY1", "KEY2", "ID")
dataset1.printSchema()
root
 |-- KEY1: string (nullable = true)
 |-- KEY2: string (nullable = true)
 |-- ID: string (nullable = true)

val selectColumns = dataset1.schema.fieldNames
selectColumns: Array[String] = Array(KEY1, KEY2, ID)

val selectColumns2 = dataset1.schema.fieldNames.toSeq 
selectColumns2: Seq[String] = WrappedArray(KEY1, KEY2, ID)

相关问题