[英]Filter columns in a Spark Scala Dataframe by a specific value when the columns are unknown
我有一个动态创建的 Spark Dataframe,当任何列为“False”时,我需要过滤 Dataframe 并将其存储在一个表中,并将其中没有任何列为假的行存储在一个表中。 永远不会知道列名和列数。
例如,如果我的表是
Col1 Col2 Col3
Row1 True False False
Row2 True True True
Row3 False False True
Row4 False False False
Output 应为表 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 中的所有行都必须为真。
任何帮助将不胜感激。 谢谢!
这是创建 DataFrame 的代码:
val df = Seq(
(true, false, false),
(true, true, true),
(false, false, true),
(false, false, false)
).toDF("col1", "col2", "col3")
让我们 append 一个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()
function 我在其中获取了此代码, 请参阅此文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.