Pyspark替换Spark数据帧列中的字符串

Luk*_*uke 22 python apache-spark pyspark

我想通过替换子字符串在Spark Dataframe列上执行一些基本的词干.最快的方法是什么?

在我目前的用例中,我有一个我想要规范化的地址列表.例如,这个数据帧:

id     address
1       2 foo lane
2       10 bar lane
3       24 pants ln
Run Code Online (Sandbox Code Playgroud)

会成为

id     address
1       2 foo ln
2       10 bar ln
3       24 pants ln
Run Code Online (Sandbox Code Playgroud)

Dan*_*ula 62

对于Spark 1.5或更高版本,您可以使用函数包:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))
Run Code Online (Sandbox Code Playgroud)

快速解释:

  • withColumn调用该函数以向数据框添加(或替换,如果名称存在)列.
  • 该函数regexp_replace将通过替换与模式匹配的所有子字符串生成新列.

  • 只要记住,regexp_replace的第一个参数是指要更改的列,第二个是要查找的正则表达式,最后一个是如何替换它。 (7认同)
  • 我们可以更改此代码中的多项吗? (4认同)

lon*_*tar 11

对于斯卡拉

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))
Run Code Online (Sandbox Code Playgroud)