scala - Scala 数据框:使用 regexp_replace 将空格替换为空值
问题描述
我正在尝试用Scala 中的null
值替换空格。regexp_replace
但是,我尝试过的所有变体都没有达到预期的输出:
+---+-----+
| Id|col_1|
+---+-----+
| 0| null|
| 1| null|
+---+-----+
我试了一下,看起来像这样:
import org.apache.spark.sql.functions._
val df = spark.createDataFrame(Seq(
(0, " "),
(1, null),
(2, "hello"))).toDF("Id", "col_1")
val test = df.withColumn("col_1", regexp_replace(df("col_1"), "^\\s*", lit(Null)))
test.filter("col_1 is null").show()
解决方案
您使用的方式regexp_replace
将不起作用,因为结果将只是一个字符串,其中匹配的子字符串替换为另一个提供的子字符串。您可以使用regexp_extract代替when/other
子句中的正则表达式相等性检查,如下所示:
import org.apache.spark.sql.functions._
val df = Seq(
(0, " "),
(1, null),
(2, "hello"),
(3, "")
).toDF("Id", "col_1")
df.withColumn("col_1",
when($"col_1" === regexp_extract($"col_1", "(^\\s*$)", 1), null).
otherwise($"col_1")
).show
// +---+-----+
// | Id|col_1|
// +---+-----+
// | 0| null|
// | 1| null|
// | 2|hello|
// | 3| null|
// +---+-----+
推荐阅读
- python-3.x - 监控 WriteToBigQuery
- systemc - SystemC中定点溢出的自动警告
- java - 如何理解 pdf 表单标志?
- eclipse - 如何删除 Eclipse JSP 文件中突出显示的行
- ios - 在 iOS 应用中获取所有选定的辅助功能选项
- c# - 从选定的文件路径获取光盘的卷标 c# winform
- eclipse - 如何在 Eclipse 4.x RCP 应用程序中以编程方式调用 Undo
- amazon-web-services - Flask 与 aws api 网关、lambda 和 dynamodb 集成
- python - 如何使用python regex从不同类型日期格式的文本中提取日期
- jvm - g1 是否收集年轻 gc 中的所有(伊甸园和幸存者)或部分垃圾?