PySpark remove special characters in all column names for all special characters

Viewed 13131

I am trying to remove all special characters from all the columns. I am using the following commands:

import pyspark.sql.functions as F

df_spark = spark_df.select([F.col(col).alias(col.replace(' ', '_')) for col in df.columns])
df_spark1 = df_spark.select([F.col(col).alias(col.replace('%', '_')) for col in df_spark.columns])
df_spark = df_spark1.select([F.col(col).alias(col.replace(',', '_')) for col in df_spark1.columns])
df_spark1 = df_spark.select([F.col(col).alias(col.replace('(', '_')) for col in df_spark.columns])
df_spark2 = df_spark1.select([F.col(col).alias(col.replace(')', '_')) for col in df_spark1.columns])

Is there an easier way of replacing all special characters (not just the 5 above) in just one command? I am using PySpark on Databricks.

4 Answers

Use re (regex) module in python with list comprehension.

Example:

df=spark.createDataFrame([('a b','ac','ac','ac','ab')],["i d","id,","i(d","i)k","i%j"])

df.columns
#['i d', 'id,', 'i(d', 'i)k', 'i%j']

import re

#replacing all the special characters using list comprehension
[re.sub('[\)|\(|\s|,|%]','',x) for x in df.columns]
#['id', 'id', 'id', 'ik', 'ij']

df.toDF(*[re.sub('[\)|\(|\s|,|%]','',x) for x in df.columns])
#DataFrame[id: string, id: string, id: string, ik: string, ij: string]

You can substitute any character except A-z and 0-9

import pyspark.sql.functions as F
import re

df = df.select([F.col(col).alias(re.sub("[^0-9a-zA-Z$]+","",col)) for col in df.columns])

re.sub('[^\w]', '_', c) replaces punctuation and spaces to _ underscore.

Test results:

from pyspark.sql import SparkSession
import re

spark = SparkSession.builder.getOrCreate()
df = spark.createDataFrame([(1, 2, 3, 4)], [' 1', '%2', ',3', '(4)'])

df = df.toDF(*[re.sub('[^\w]', '_', c) for c in df.columns])
df.show()

#  +---+---+---+---+
#  | _1| _2| _3|_4_|
#  +---+---+---+---+
#  |  1|  2|  3|  4|
#  +---+---+---+---+

Removing punctuation + putting _ instead of spaces:

re.sub('[^\w ]', '', c).replace(' ', '_')

perhaps this is useful -

 // [^0-9a-zA-Z]+ => this will remove all special chars
    spark.range(2).withColumn("str", lit("abc%xyz_12$q"))
      .withColumn("replace", regexp_replace($"str", "[^0-9a-zA-Z]+", "_"))
      .show(false)

    /**
      * +---+------------+------------+
      * |id |str         |replace     |
      * +---+------------+------------+
      * |0  |abc%xyz_12$q|abc_xyz_12_q|
      * |1  |abc%xyz_12$q|abc_xyz_12_q|
      * +---+------------+------------+
      */

    // if you don't want to remove some special char like $ etc, include it [^0-9a-zA-Z$]+
    spark.range(2).withColumn("str", lit("abc%xyz_12$q"))
      .withColumn("replace", regexp_replace($"str", "[^0-9a-zA-Z$]+", "_"))
      .show(false)

    /**
      * +---+------------+------------+
      * |id |str         |replace     |
      * +---+------------+------------+
      * |0  |abc%xyz_12$q|abc_xyz_12$q|
      * |1  |abc%xyz_12$q|abc_xyz_12$q|
      * +---+------------+------------+
      */
Related