scala - 当列未知时,按特定值过滤 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 中的所有行都必须为真。
任何帮助将不胜感激。谢谢!
解决方案
这是创建 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()
功能,我在其中获取了此代码,请参阅此文件。
推荐阅读
- swift - 如何修复 cocoapod .modulemap 文件未找到
- c - C 语言中的 Diffie-Helman 程序
- html - 一旦达到最大高度,如何使用 CSS 减小 div 的宽度?
- vba - 如何从输入框中提取行号
- vue.js - 处理一个元素上的不同点击事件
- javascript - 如何在按下按钮后禁用它,然后重新启用它?
- javascript - Nodejs MaxListenersExceededWarning 在 aws lambda 中限制了堆栈跟踪
- python - TensorFlow 中的自动编码器
- javascript - 从数组中过滤出具有匹配两个值的差异的对象
- rest - REST URIs 案例和有效负载案例