首页 > 解决方案 > 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()

标签: scalanullregexp-replace

解决方案


您使用的方式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|
// +---+-----+

推荐阅读