How to replace column values using regular expression in PySpark Azure Databricks?

Are you looking to find out how to replace column values in PySpark using Azure Databricks cloud or maybe you are looking for a solution, to replace column value with string or substring in PySpark Databricks using the regexp_replace() function? If you are looking for any of these problem solutions, you have landed on the correct page. I will also show you how to use PySpark to replace column value using the regexp_replace() function in Azure Databricks. I will explain it by taking a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to use the regexp_replace() function in PySpark.

In this blog, I will teach you the following with practical examples:

  • Syntax of regexp_replace()
  • Replacing column values
  • Replacing column values conditionally
  • Replacing column values with regex pattern

The PySpark’s regexp_replace() function is a SQL string function used to replace a column value with a string or substring. If no match was found, the column value remains unchanged.

Syntax:

regexp_replace(column_name, matching_value, replacing_value)

What is the syntax of the regexp_replace() function in PySpark Azure Databricks?

The syntax is as follows:

regexp_replace(column_name, matching_value, replacing_value)
Parameter NameRequiredDescription
column_nameYesIt represents the column name.
matching_valueYesIt represents the pattern that needs to be replaced.
replacing_valueYesIt represents the value that needs to be replaced by.
Table 1: regexp_replace() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: regexp_replace()

Create a simple DataFrame

Let’s understand the use of the regexp_replace() function with various examples. Let’s start by creating a DataFrame.

Gentle reminder:

In Databricks,

  • sparkSession made available as spark
  • sparkContext made available as sc

In case, you want to create it manually, use the below code.

from pyspark.sql.session import SparkSession

spark = SparkSession.builder 
    .master("local[*]") 
    .appName("azurelib.com") 
    .getOrCreate()

sc = spark.sparkContext

a) Create manual PySpark DataFrame

data = [
    (1, "Male","2022-10-25"),
    (2, "Female","2021/12/17"),
    (3, "Female","18.11.2021")
]

df = spark.createDataFrame(data, schema=["id","gender","dob"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- gender: string (nullable = true)
 |-- dob: string (nullable = true)

+---+------+----------+
|id |gender|dob       |
+---+------+----------+
|1  |Male  |2022-10-25|
|2  |Female|2021/12/17|
|3  |Female|18.11.2021|
+---+------+----------+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

# replace the file_path with the source file location which you have downloaded.

df_2 = spark.read.format("csv").option("header", True).load(file_path)
df_2.printSchema()

"""
root
 |-- id: long (nullable = true)
 |-- gender: string (nullable = true)
 |-- dob: string (nullable = true)
"""

Note: Here, I will be using the manually created DataFrame.

How to replace column values in PySpark Azure Databricks?

Let’s see how to replace column value with string or substring of PySpark DataFrame in Azure Databricks.

Example 1:

In this example, let’s try to replace the value “Male” with “M”. Note that the pattern is case-sensitive.

# Using select()

from pyspark.sql.functions import regexp_replace

df.select("gender", regexp_replace("gender", "Male", "M").alias("male_replace")).show()

"""
Output:

+------+------------+
|gender|male_replace|
+------+------------+
|  Male|           M|
|Female|      Female|
|Female|      Female|
+------+------------+


"""

Example 2:

In this example, let’s try to replace the value “Female” with “Fm”. Note that the pattern is case-sensitive.

# Using withColumn()

from pyspark.sql.functions import regexp_replace

df.withColumn("female_replace", regexp_replace("gender", "Female", "Fm"))\
.select("gender", "female_replace").show()

"""
Output:

+------+--------------+
|gender|female_replace|
+------+--------------+
|  Male|          Male|
|Female|            Fm|
|Female|            Fm|
+------+--------------+

"""

How to replace column values conditionally in PySpark Azure Databricks?

Let’s see how to replace column values conditionally of PySpark DataFrame in Azure Databricks.

Let’s try to replace the following column values in this example:

  • “Male” with “M”
  • “Female” with “Fm”

Example:

from pyspark.sql.functions import regexp_replace, when, col

df.select("gender", 
          when(col("gender").startswith("M"), regexp_replace("gender", "Male", "M")) \
          .when(col("gender").startswith("F"), regexp_replace("gender", "Female", "Fm")) \
          .otherwise(col("gender")).alias("regex_conditional")).show()

"""
Output:

+------+-----------------+
|gender|regex_conditional|
+------+-----------------+
|  Male|                M|
|Female|               Fm|
|Female|               Fm|
+------+-----------------+

"""

How to replace column values using regular expressions in PySpark Azure Databricks?

Let’s see how to replace column values using the regexp pattern of a PySpark DataFrame in Azure Databricks.

Note: In PySpark the pattern uses Java Regex

Example:

In this example, let’s try to replace the multiple delimiters with “-” found on each record using regular expressions.

from pyspark.sql.functions import regexp_replace

df.select("dob", regexp_replace("dob", "[/.]", "-").alias("mod_dob")).show()

"""
Output:

+----------+----------+
|       dob|   mod_dob|
+----------+----------+
|2022-10-25|2022-10-25|
|2021/12/17|2021-12-17|
|18.11.2021|18-11-2021|
+----------+----------+

"""

I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.

When should you use the PySpark regexp_replace() in Azure Databricks?

You should use the PySpark regexp_replace() function to replace column values using the Java Regular expression.

Real World Use Case Scenarios for PySpark DataFrame regexp_replace() in Azure Databricks?

  • Assume that you were given an abbreviated gender column, for example, the values look like ‘M’ and ‘Fm’ which represent male and female respectively. You have been asked to replace the abbreviated column with an extended one. You can do this with the help of the regexp_replace() method.
  • Assume that you were given a date column of StringType. The date column values are separated by using different delimiters and you have asked to replace all delimiter values with ‘-‘. For example ‘2020/11/08’ and ‘2022.11.09’ to ‘2022-11-08’ and ‘2022-11-09’. You can perform this activity by using the PySpark regexp_replace() function.

What are the alternatives to the regexp_replace() function in PySpark Azure Databricks?

There are multiple alternatives to the regexp_replace() function, which are as follows:

  • regexpr_replace(): used for replacing column values using regular expression.
  • overlay(): used for replacing a source column with replacing column value starting from a position and proceeding for length.
  • substring(): used for extracting a column from an index and proceeding value.
  • translate(): used for replacing column characters with another

Final Thoughts

In this article, we have learned about the PySpark regexp_replace() method to replace column values of DataFrame in Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.

Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.

Arud Seka Berne S

As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.