【问题标题】:how to use Regexp_replace in spark如何在火花中使用 Regexp_replace
【发布时间】:2017-02-26 02:18:34
【问题描述】:

我对 spark 很陌生,想对数据框的列执行操作,以便将列中的所有 , 替换为 .

假设有一个数据框 x 和 x4 列

x4
1,3435
1,6566
-0,34435

我希望输出为

x4
1.3435
1.6566
-0.34435

我使用的代码是

import org.apache.spark.sql.Column
def replace = regexp_replace((x.x4,1,6566:String,1.6566:String)x.x4)

但我收到以下错误

import org.apache.spark.sql.Column
<console>:1: error: ')' expected but '.' found.
       def replace = regexp_replace((train_df.x37,0,160430299:String,0.160430299:String)train_df.x37)

任何有关语法、逻辑或任何其他合适方式的帮助将不胜感激

【问题讨论】:

    标签: scala apache-spark apache-spark-sql regexp-replace


    【解决方案1】:

    这是一个可重现的示例,假设 x4 是一个字符串列。

    import org.apache.spark.sql.functions.regexp_replace
    
    val df = spark.createDataFrame(Seq(
      (1, "1,3435"),
      (2, "1,6566"),
      (3, "-0,34435"))).toDF("Id", "x4")
    

    语法为regexp_replace(str, pattern, replacement),翻译为:

    df.withColumn("x4New", regexp_replace(df("x4"), "\\,", ".")).show
    +---+--------+--------+
    | Id|      x4|   x4New|
    +---+--------+--------+
    |  1|  1,3435|  1.3435|
    |  2|  1,6566|  1.6566|
    |  3|-0,34435|-0.34435|
    +---+--------+--------+
    

    【讨论】:

    • 我可以用多个字符代替逗号吗?例如,我想用任何其他字符替换逗号感叹号?
    • 您想用一个字符替换多个特殊字符吗?是的,这是可能的。
    • 我试过但没用。你能告诉我怎么做吗?
    • 你可以试试regexp_replace(df.col, "[\\?,\\.,\\$]", "."))
    【解决方案2】:

    我们可以使用map 方法进行这种转换:

    scala> df.map(each => { 
    (each.getInt(0),each.getString(1).replaceAll(",", "."))
    })
    .toDF("Id","x4")
    .show
    
    Output:
    
    +---+--------+
    | Id|      x4|
    +---+--------+
    |  1|  1.3435|
    |  2|  1.6566|
    |  3|-0.34435|
    +---+--------+
    

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 1970-01-01
      • 2018-08-09
      • 2020-04-25
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      相关资源
      最近更新 更多