Scala dataframe:使用regexp\u replace用空值替换空格

Scala dataframe:使用regexp\u replace用空值替换空格,scala,null,regexp-replace,Scala,Null,Regexp Replace,我试图使用Scala中的regexp\u replace将空格替换为null值。但是,我尝试过的所有变体都没有达到预期的输出: +---+-----+ | Id|col_1| +---+-----+ | 0| null| | 1| null| +---+-----+ 我试了一下,看起来是这样的: import org.apache.spark.sql.functions._ val df = spark.createDataFrame(Seq( (0, " "), (1, n

我试图使用Scala中的
regexp\u replace
将空格替换为
null
值。但是,我尝试过的所有变体都没有达到预期的输出:

+---+-----+
| 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\u replace
的方法不起作用,因为结果只是一个字符串,匹配的子字符串被另一个提供的子字符串替换。您可以改为在
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|
// +---+-----+