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



我有一个这样的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

正则表达式中有一个拼写错误,在下面的代码中修复了它

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)
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|
+----+----+
+----+----+

最新更新