首页 > 解决方案 > 当列未知时,按特定值过滤 Spark Scala 数据框中的列

问题描述

我有一个动态创建的 Spark Dataframe,当任何列为“False”时,我需要过滤 Dataframe,并将其存储在一个表中,并将没有任何列为 false 的行存储在一个表中。永远不会知道列名和列数。

例如,如果我的表是

     Col1  Col2   Col3
Row1    True  False  False
Row2    True  True   True
Row3    False False  True
Row4    False False  False

输出应为表 1:

    Col1  Col2   Col3
Row1    True  False  False
Row3    False False  True
Row4    False False  False

和表 2

    Col1  Col2   Col3
Row2    True  True   True

我努力了:

val columns: Array[String] = testDF.columns
val seqDfs: Seq[DataFrame] = columns.map(name => df.filter(s"$name == 'False'"))
val output: DataFrame = seqDfs.reduceRight(_ union _)

但它返回了很多重复值,即使我清除了重复值,它也无助于我创建表 2,因为表 2 中的所有行都必须为真。

任何帮助将不胜感激。谢谢!

标签: scaladataframeapache-spark

解决方案


这是创建 DataFrame 的代码:

val df = Seq(
  (true, false, false), 
  (true, true, true),
  (false, false, true),
  (false, false, false)
).toDF("col1", "col2", "col3")

让我们追加一all_true列:

val columns = df.columns
val df2 = df.withColumn("all_true", columns.map(col(_).===(true)).reduceLeft(_.&&(_)))

这是具有所有真实值的 DataFrame:

df2.where($"all_true" === true).drop("all_true").show()

+----+----+----+
|col1|col2|col3|
+----+----+----+
|true|true|true|
+----+----+----+

这是 DataFrame 的值并非全部为真:

df2.where($"all_true" === false).drop("all_true").show()

+-----+-----+-----+
| col1| col2| col3|
+-----+-----+-----+
| true|false|false|
|false|false| true|
|false|false|false|
+-----+-----+-----+

好问题,欢迎来到 StackOverflow ;)

顺便说一句,spark-daria有一个multiEquals()功能,我在其中获取了此代码,请参阅此文件


推荐阅读