如何在Spark中使用Regexp_replace

18

我对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)
任何关于语法、逻辑或其他合适方法的帮助将不胜感激。
2个回答

33

以下是一个可重现的例子,假设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|
+---+--------+--------+

1
我可以使用多个字符代替逗号吗?例如,我想用其他字符替换逗号、句点和感叹号。 - Abu Shoeb
你想把多个特殊字符替换成一个字符吗?是的,这是可能的。 - mtoto
我尝试了但没有成功。能告诉我怎么做吗? - Abu Shoeb
2
你可以尝试类似这样的代码:regexp_replace(df.col, "[\\?,\\.,\\$]", ".") - mtoto

-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|
+---+--------+

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接