从spark scala DataFrame中选择名称包含特定字符串的列。

问题描述 投票:0回答:1

我有一个这样的DataFrame。

Name   City  Name_index   City_index
Ali    lhr     2.0          0.0
abc    swl     0.0          2.0
xyz    khi     1.0          1.0

我想删除不包含 "index "等字符串的列。

预期的输出应该是这样的。

Name_index   City_index
 2.0           0.0
 0.0           2.0
 1.0           1.0

我已经试过了

val cols = newDF.columns
    val regex = """^((?!_indexed).)*$""".r
    val selection = cols.filter(s => regex.findFirstIn(s).isDefined)
    cols.diff(selection)
    val res =newDF.select(selection.head, selection.tail : _*)
    res.show()

但我得到的是这样的结果。

Name   City
Ali    lhr
abc    swl
xyz    khi
regex scala apache-spark
1个回答
1
投票

在你的regex中有一个错别字,在下面的代码中修正了它。

import org.apache.spark.sql.SparkSession

object FilterColumn {

  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder().master("local[*]").getOrCreate()
    import spark.implicits._
    val newDF = List(PersonCity("Ali","lhr",2.0,0.0)).toDF()
    newDF.show()
    val cols = newDF.columns
    val regex = """^((?!_index).)*$""".r
    val selection = cols.filter(s => regex.findFirstIn(s).isDefined)
    val finalCols = cols.diff(selection)
    val res =newDF.select(finalCols.head,finalCols.tail: _*)
    res.show()
  }

}

case class PersonCity(Name : String,   City :String, Name_index : Double,   City_index: Double)

0
投票
import org.apache.spark.sql.functions.col

val regex = """^((?!_indexed).)*$""".r
val schema = StructType(
      Seq(StructField("Name", StringType, false),
          StructField("City", StringType, false),
          StructField("Name_indexed", IntegerType, false),
          StructField("City_indexed", LongType, false)))

val empty: DataFrame = spark.createDataFrame(spark.sparkContext.emptyRDD[Row], schema = schema)
val columns = schema.map(_.name).filter(el => regex.pattern.matcher(el).matches())
empty.select(columns.map(col):_*).show()

它给

+----+----+
|Name|City|
+----+----+
+----+----+
© www.soinside.com 2019 - 2024. All rights reserved.