Pyspark删除数据框列中的多个字符

E B*_*E B 2 translate regexp-replace pyspark

看着pyspark,我看到translation和regexp_replace可以帮助我在dataframe列中存在一个字符。

我想知道是否有一种方法可以在regexp_replace中提供多个字符串或进行翻译,以便它可以解析它们并将它们替换为其他内容。

用例:删除列A中的所有$,#和逗号(,)

pau*_*ult 6

您可以pyspark.sql.functions.translate()用来进行多次替换。输入一串字母来替换,并输入另一个等长的字符串来表示替换值。

例如,假设您具有以下DataFrame:

import pyspark.sql.functions as f
df = sqlCtx.createDataFrame([("$100,00",),("#foobar",),("foo, bar, #, and $",)], ["A"])
df.show()
#+------------------+
#|                 A|
#+------------------+
#|           $100,00|
#|           #foobar|
#|foo, bar, #, and $|
#+------------------+
Run Code Online (Sandbox Code Playgroud)

并希望替换('$', '#', ',')('X', 'Y', 'Z')。只需使用translate像:

df.select("A", f.translate(f.col("A"), "$#,", "XYZ").alias("replaced")).show()
#+------------------+------------------+
#|                 A|          replaced|
#+------------------+------------------+
#|           $100,00|           X100Z00|
#|           #foobar|           Yfoobar|
#|foo, bar, #, and $|fooZ barZ YZ and X|
#+------------------+------------------+
Run Code Online (Sandbox Code Playgroud)

相反,如果您想删除的所有实例('$', '#', ','),则可以使用进行操作pyspark.sql.functions.regexp_replace()

df.select("A", f.regexp_replace(f.col("A"), "[\$#,]", "").alias("replaced")).show()
#+------------------+-------------+
#|                 A|     replaced|
#+------------------+-------------+
#|           $100,00|        10000|
#|           #foobar|       foobar|
#|foo, bar, #, and $|foo bar  and |
#+------------------+-------------+
Run Code Online (Sandbox Code Playgroud)

模式"[\$#,]"表示匹配括号内的任何字符。该$来转义,因为它在正则表达式特殊的意义。