[英]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.