Spark (Scala):如何将 Array[Row] 转换为 DataSet[Row] 或 DataFrame?
Spark (Scala): How to turn an Array[Row] into either a DataSet[Row] or a DataFrame?
我有一个 Array[Row],我想将它变成 Dataset[Row]
或 DataFrame
。
我是怎么想出行数组的?
好吧,我正试图从我的数据集中清除空值:
- 无需 过滤每一列(我有很多列)并且..
- 没有 使用
DataFrameNaFunctions
中的 .na.drop()
函数,因为它无法检测单元格何时实际具有字符串 "null"
.
所以,我想到了以下行来过滤掉所有列中的 null
。
val outDF = inputDF.columns.flatMap { col => inputDF.filter(col + "!='' AND " + col + "!='null'").collect() }
问题是,outDF 是一个 Array[Row]
,因此问题来了!欢迎任何想法!
这就是您的代码如果有效的话会执行的操作:
inputDF.columns.map {
col => inputDF.filter((inputDF(col) =!= "") and (inputDF(col) =!= "null"))
}.reduce(_ union _)
还有这样的东西:
inputDF.where(inputDF.columns.map {
col => (inputDF(col) =!= "") and (inputDF(col) =!= "null")
}.foldLeft(lit(true))(_ and _))
就是你想要的。
请注意,第一个解决方案创建非独占子集,因此数据如下:
val inputDF = Seq(("1", "a"), ("2", ""), ("null", "")).toDF
结果将是:
+---+---+
| _1| _2|
+---+---+
| 1| a|
| 2| |
| 1| a|
+---+---+
对于我认为正确的解决方案:
+---+---+
| _1| _2|
+---+---+
| 1| a|
+---+---+
根据 Srinivas 先生的评论,使用以下代码回答了这个问题:
//First drop all typical nulls
val prelimDF = inputDF.na.drop()
//Then drops all columns actually saying 'null'
val finalDF = prelimDF.na.drop(prelimDF.columns).where("'null' not in ("+prelimDF.columns.mkString(",")+")")
干杯!
我根据我的评论发布答案。
df.na.drop(df.columns).where("'null' not in ("+df.columns.mkString(",")+")")
我有一个 Array[Row],我想将它变成 Dataset[Row]
或 DataFrame
。
我是怎么想出行数组的?
好吧,我正试图从我的数据集中清除空值:
- 无需 过滤每一列(我有很多列)并且..
- 没有 使用
DataFrameNaFunctions
中的.na.drop()
函数,因为它无法检测单元格何时实际具有字符串"null"
.
所以,我想到了以下行来过滤掉所有列中的 null
。
val outDF = inputDF.columns.flatMap { col => inputDF.filter(col + "!='' AND " + col + "!='null'").collect() }
问题是,outDF 是一个 Array[Row]
,因此问题来了!欢迎任何想法!
这就是您的代码如果有效的话会执行的操作:
inputDF.columns.map {
col => inputDF.filter((inputDF(col) =!= "") and (inputDF(col) =!= "null"))
}.reduce(_ union _)
还有这样的东西:
inputDF.where(inputDF.columns.map {
col => (inputDF(col) =!= "") and (inputDF(col) =!= "null")
}.foldLeft(lit(true))(_ and _))
就是你想要的。
请注意,第一个解决方案创建非独占子集,因此数据如下:
val inputDF = Seq(("1", "a"), ("2", ""), ("null", "")).toDF
结果将是:
+---+---+
| _1| _2|
+---+---+
| 1| a|
| 2| |
| 1| a|
+---+---+
对于我认为正确的解决方案:
+---+---+
| _1| _2|
+---+---+
| 1| a|
+---+---+
根据 Srinivas 先生的评论,使用以下代码回答了这个问题:
//First drop all typical nulls
val prelimDF = inputDF.na.drop()
//Then drops all columns actually saying 'null'
val finalDF = prelimDF.na.drop(prelimDF.columns).where("'null' not in ("+prelimDF.columns.mkString(",")+")")
干杯!
我根据我的评论发布答案。
df.na.drop(df.columns).where("'null' not in ("+df.columns.mkString(",")+")")