【问题标题】:Scala dataframe: replace spaces with null value using regexp_replaceScala 数据框:使用 regexp_replace 将空格替换为空值
【发布时间】:2019-03-31 16:15:00
【问题描述】:

我正在尝试在 Scala 中使用 regexp_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()

【问题讨论】:

    标签: scala null regexp-replace


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-09
      • 2017-05-29
      • 1970-01-01
      • 2019-06-09
      • 2020-11-29
      • 2012-05-15
      • 2022-12-06
      • 2016-10-16
      相关资源
      最近更新 更多