如何替换 Spark 数据帧所有列中的多个字符?

Nep*_*ner 5 python replace apache-spark apache-spark-sql pyspark

我有一个包含多列的数据框。

>>> df.take(1)
[Row(A=u'{dt:dt=string, content=Prod}', B=u'{dt:dt=string, content=Staging}')]
Run Code Online (Sandbox Code Playgroud)

我想从 'A' 和 'B' 列的值中删除两个大括号{和. 我知道我们可以使用:}df

df.withColumn('A', regexp_replace('A', '//{', ''))
df.withColumn('A', regexp_replace('A', '//}', ''))
df.withColumn('B', regexp_replace('B', '//}', ''))
Run Code Online (Sandbox Code Playgroud)

如何动态替换 Spark 数据帧所有列的字符?(Pandas版本如下所示)

df = df.replace({'{':'', '}':''}, regex=True)
Run Code Online (Sandbox Code Playgroud)

小智 2

只需使用正确的正则表达式:

df.withColumn("A", regexp_replace("A", "[{}]", ""))
Run Code Online (Sandbox Code Playgroud)

  • 我们如何将上述语句同时应用于多个列?假设我的数据框中有 10 列。 (2认同)