scala - 使用 Spark (1.6) 从 Scala 中 Dataframe 中的数组列中删除 Null
问题描述
我有一个带有键列的数据框和一个具有结构数组的列。架构如下所示。
root
|-- id: string (nullable = true)
|-- desc: array (nullable = false)
| |-- element: struct (containsNull = true)
| | |-- name: string (nullable = true)
| | |-- age: long (nullable = false)
数组“desc”可以有任意数量的空值。我想使用 spark 1.6 创建一个最终的数据框,其中的数组没有任何空值:
一个例子是:
Key . Value
1010 . [[George,21],null,[MARIE,13],null]
1023 . [null,[Watson,11],[John,35],null,[Kyle,33]]
我希望最终的数据框为:
Key . Value
1010 . [[George,21],[MARIE,13]]
1023 . [[Watson,11],[John,35],[Kyle,33]]
我尝试使用 UDF 和案例类执行此操作,但得到了
java.lang.ClassCastException: org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema cannot be cast to....
非常感谢任何帮助,如果需要,我宁愿这样做而不转换为 RDD。我也是 spark 和 scala 的新手,所以提前谢谢!!!
解决方案
这是另一个版本:
case class Person(name: String, age: Int)
root
|-- id: string (nullable = true)
|-- desc: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- name: string (nullable = true)
| | |-- age: integer (nullable = false)
+----+-----------------------------------------------+
|id |desc |
+----+-----------------------------------------------+
|1010|[[George,21], null, [MARIE,13], null] |
|1023|[[Watson,11], null, [John,35], null, [Kyle,33]]|
+----+-----------------------------------------------+
val filterOutNull = udf((xs: Seq[Row]) => {
xs.flatMap {
case null => Nil
// convert the Row back to your specific struct:
case Row(s: String,i: Int) => List(Person(s, i))
}
})
val result = df.withColumn("filteredListDesc", filterOutNull($"desc"))
+----+-----------------------------------------------+-----------------------------------+
|id |desc |filteredListDesc |
+----+-----------------------------------------------+-----------------------------------+
|1010|[[George,21], null, [MARIE,13], null] |[[George,21], [MARIE,13]] |
|1023|[[Watson,11], null, [John,35], null, [Kyle,33]]|[[Watson,11], [John,35], [Kyle,33]]|
+----+-----------------------------------------------+-----------------------------------+
推荐阅读
- google-apps-script - 如何使用谷歌脚本将我的所有电子邮件从我的旧 gmail 帐户转发到新的 gmail 帐户
- html - 引导布局:获得两个滚动条
- c# - 使用存储过程在数据库中搜索
- unit-testing - 如何在 golang 中动态跳过测试?
- ada - 后置条件的含义
- excel - Excel VBA让用户输入新的工作表名称
- google-cloud-platform - setIAM 403 禁止
- azure - 在 Xamarin 表单应用程序中尝试 O365 身份验证
- python - Python - 如何将多维列表排序为二维列表?
- c# - 如何使用凭据制作批处理脚本以在远程计算机上运行命令