gpt4 book ai didi

scala - 在 spark 中通过验证转换 Dataframe 列

转载 作者:行者123 更新时间:2023-12-04 19:52:02 26 4
gpt4 key购买 nike

我需要将包含所有字符串值的数据框列转换为定义的模式数据类型。在进行转换时,我们需要将损坏的记录(数据类型错误的记录)放入单独的列中

数据框示例

+---+----------+-----+
|id |name |class|
+---+----------+-----+
|1 |abc |21 |
|2 |bca |32 |
|3 |abab | 4 |
|4 |baba |5a |
|5 |cccca | |
+---+----------+-----+

文件的Json架构:

 {"definitions":{},"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://example.com/root.json","type":["object","null"],"required":["id","name","class"],"properties":{"id":{"$id":"#/properties/id","type":["integer","null"]},"name":{"$id":"#/properties/name","type":["string","null"]},"class":{"$id":"#/properties/class","type":["integer","null"]}}}

在这一行中,第 4 行是损坏的记录,因为类列是 Integer 类型所以只有这条记录必须存在于损坏的记录中,而不是第 5 行

最佳答案

只需在转换前检查值是否为 NOT NULL 以及在转换后是否为 NULL

import org.apache.spark.sql.functions.when

df
.withColumn("class_integer", $"class".cast("integer"))
.withColumn(
"class_corrupted",
when($"class".isNotNull and $"class_integer".isNull, $"class"))

为您需要的每一列/类型转换重复。

关于scala - 在 spark 中通过验证转换 Dataframe 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56698044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com