scala - 数组类型列中元素的数据类型修改
问题描述
我有一个具有以下模式的数据框,用于列 col。
col:array
element:struct
Id:string
Seq:int
Pct:double
Amt:long
当数据不可用时,下面是结构
col:array
element:string
该列可以包含数据并且可以为空。
当数据可用时,它的来源格式如下:
{"Id": "123456-1", "Seq": 1, "Pct": 0.1234, "Amt": 3000}
当数据不可用时,我将默认设置如下:
.withColumn("col", when (size($"col") === 0, array(lit("A").cast("string"), lit(0).cast("int"), lit(0.0).cast("double"))).otherwise($"col")
对于我得到的空数据,数据似乎被转换为字符串:
["A", "0", "0.0", "0.0"]
如何获得以下输出:
{"Id": "A", "Seq": 0, "Pct": 0.0}
当数据在以下源中可用时是输出:
+----------------------------------------------------+
| Data |
+----------------------------------------------------+
|[[236711-1, 0.14, 1.5, 1], [236711-1, 0.14, 2.0, 2]]|
|[[1061605-1, 0.011, 1.0, 1]] |
+----------------------------------------------------+
数据不可用时
| Data |
+------+
|[] |
+------+
解决方案
您可以创建一个结构的数组而不是数组:
val df2 = df.withColumn(
"col",
df.schema("col").dataType match {
case ArrayType(StringType, _) =>
array(
struct(
lit("A").cast("string").as("Id"),
lit(0).cast("int").as("Seq"),
lit(0.0).cast("double").as("Pct")
)
)
case ArrayType(StructType(_), _) => $"col"
}
)
推荐阅读
- arrays - 有没有一种简单的方法可以使用小脚本自动读取文本文件并使用带有 awk 或其他 unix 命令的 bash 脚本进行绘图?
- c# - 带有不同 WHERE 子句的 SELECT
- core-data - 创建一个 NSManagedObject 并注入一个 SwiftUI 视图,该视图会自动添加到导航堆栈中
- swift - iOS - 将字符串拆分为关键字和短语
- docker-swarm - 无法使用连接到同一 VCN 的 Oracle Cloud VM 加入 docker swarm
- php - Html 和 css 到电子邮件 php laravel
- javascript - 赛普拉斯 - 错误消息与代码不匹配
- c++ - CSES - 不同的颜色
- php - WooCommerce 针对特定产品类别的累进数量折扣
- css - CSS网格没有调整到屏幕的宽度