我正在尝试在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()
答案 0 :(得分:1)
您使用regexp_replace
的方式将不起作用,因为结果将只是将匹配的子字符串替换为另一个提供的子字符串的字符串。您可以在when/other
子句中使用regexp_extract进行正则表达式相等性检查,如下所示:
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|
// +---+-----+