如何从 Spark 数据框中的所有列中删除反斜杠? [英] How to remove backslash from all columns in a Spark dataframe?

查看:28
本文介绍了如何从 Spark 数据框中的所有列中删除反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 spark DF 中的多列中删除属于字符串一部分的所有 \ 字符?

How can I remove all \ characters that are a part of strings from multiple columns in a spark DF?

样本行:

11~ADX\|0.00\|ZZ\|BP\|WHT~SE\|41\|0064~GE\|0001\

预期输出:

11~ADX|0.00|ZZ|BP|WHT~SE|41|0064~GE|0001

推荐答案

在数据框中的所有列上使用 foldLeft,这样你就可以在每个单独的列上使用 regexp_replace列并返回最终的数据帧.使用问题中的示例数据框(下面称为 df),删除所有反斜杠:

Use foldLeft on all columns in the dataframe, in this way you can use regexp_replace on each separate column and return the final dataframe. Using the example dataframe in the question (called df below), to remove all backslashes:

val df2 = df.columns.foldLeft(df)((df, c) => df.withColumn(c, regexp_replace(col(c), "\\\\", "")))

您也可以使用以下内容转义所有反斜杠:

You could also escape all backslashes with the following:

val df2 = df.columns.foldLeft(df)((df, c) => df.withColumn(c, regexp_replace(col(c), "\\\\", "\\\\\\\\")))

<小时>

如果不是所有的列都应该使用,创建一个单独的变量来包含要使用的列.要使用除一列之外的所有列(下面的列 col),请使用:

val cols = df.columns diff List("col")
cols.foldLeft ...

这篇关于如何从 Spark 数据框中的所有列中删除反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆