How to replace specific portion of a column value in PySpark Azure Databricks?

Are you looking to find out how to one column value with another column in PySpark using Azure Databricks cloud or maybe you are looking for a solution, to replace specific portion of a column value with another column value in PySpark Databricks using the overlay() 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 overlay() 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 overlay() function in PySpark.

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

  • Syntax of overlay()
  • Replacing one column value with another
  • Replacing a specific portion of a column value with another

The PySpark’s overlay() function is a SQL string function used to replace a column value or a specific position of a column value with another.

Syntax:

overlay()

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

The syntax is as follows:

overlay(source_column, replace_column, start_position, length)
Parameter NameRequiredDescription
source_columnYesIt represents the column that has to be replaced.
replace_columnYesIt represents the column that has to be replaced by.
start_positionYesIt represents the source column index position from which the replacement has to begin with.
lengthOptionalIt represents the source column length of characters to be removed from the start position.
Table 1: overlay() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: overlay()

Create a simple DataFrame

Let’s understand the use of the regexp_replace() function with a variety of 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,"Mrs.","12_Gal","M","Male"),
    (2,"Dr.","12_Nichol","F","Female"),
    (3,"Rev.","12_Ileane","F","Female"),
    (4,"Rev.","12_Jeffry","M","Male"),
    (5,"Ms.","12_Aryn","F","Female")
]

df = spark.createDataFrame(data, schema=["id","title","name","gender_1","gender_2"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- title: string (nullable = true)
 |-- name: string (nullable = true)
 |-- gender_1: string (nullable = true)
 |-- gender_2: string (nullable = true)

+---+-----+---------+--------+--------+
|id |title|name     |gender_1|gender_2|
+---+-----+---------+--------+--------+
|1  |Mrs. |12_Gal   |M       |Male    |
|2  |Dr.  |12_Nichol|F       |Female  |
|3  |Rev. |12_Ileane|F       |Female  |
|4  |Rev. |12_Jeffry|M       |Male    |
|5  |Ms.  |12_Aryn  |F       |Female  |
+---+-----+---------+--------+--------+
"""

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)
 |-- title: string (nullable = true)
 |-- name: string (nullable = true)
 |-- gender_1: string (nullable = true)
 |-- gender_2: string (nullable = true)
"""

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

How to replace one column value with another in PySpark Azure Databricks?

Let’s see how to replace one column value with another column of PySpark DataFrame in Azure Databricks.

Example:

In this example, let’s try to replace the column “gender_1” with “gender_2”.

from pyspark.sql.functions import overlay

df.withColumn("gender_1", overlay("gender_1", "gender_2", 1)).show()

"""
Output:

+---+-----+------+--------+--------+
| id|title|  name|gender_1|gender_2|
+---+-----+------+--------+--------+
|  1| Mrs.|   Gal|    Male|    Male|
|  2|  Dr.|Nichol|  Female|  Female|
|  3| Rev.|Ileane|  Female|  Female|
|  4| Rev.|Jeffry|    Male|    Male|
|  5|  Ms.|  Aryn|  Female|  Female|
+---+-----+------+--------+--------+


"""

How to replace specific portion of a column with another column in PySpark Azure Databricks?

Let’s see how to replace a specific portion of a column with another column of PySpark DataFrame in Azure Databricks.

Let’s try to achieve the name of the person to be like <title><proper_name> for example: “12_Jeffry” to “Rev.Jeffry” using the trial and error method.

Trail 1:

from pyspark.sql.functions import overlay

df \
.withColumn("title_name", overlay("name", "title", 1)) \
.select("id", "title", "title_name").show()

"""
Output:

+---+-----+----------+
| id|title|title_name|
+---+-----+----------+
|  1| Mrs.|    Mrs.al|
|  2|  Dr.| Dr.Nichol|
|  3| Rev.| Rev.leane|
|  4| Rev.| Rev.effry|
|  5|  Ms.|   Ms.Aryn|
+---+-----+----------+

"""

Since we haven’t specified the number string to be replaced from the source column, the overlay() function automatically removed it based on the length of replacing column value.

Trail 2:

from pyspark.sql.functions import overlay

df \
.withColumn("title_name", overlay("name", "title", 1, 0)) \
.select("id", "title", "name", "title_name").show()

"""
Output:

+---+-----+---------+-------------+
| id|title|     name|   title_name|
+---+-----+---------+-------------+
|  1| Mrs.|   12_Gal|   Mrs.12_Gal|
|  2|  Dr.|12_Nichol| Dr.12_Nichol|
|  3| Rev.|12_Ileane|Rev.12_Ileane|
|  4| Rev.|12_Jeffry|Rev.12_Jeffry|
|  5|  Ms.|  12_Aryn|   Ms.12_Aryn|
+---+-----+---------+-------------+

"""

As you can see we have specified the number of characters to be replaced from the source column to be 0, and no character from the start position has been removed. But, this is not the output we want.

Trail 3:

from pyspark.sql.functions import overlay

df \
.withColumn("title_name", overlay("name", "title", 1, 3)) \
.select("id", "title", "name", "title_name").show()

"""
Output:

+---+-----+---------+----------+
| id|title|     name|title_name|
+---+-----+---------+----------+
|  1| Mrs.|   12_Gal|   Mrs.Gal|
|  2|  Dr.|12_Nichol| Dr.Nichol|
|  3| Rev.|12_Ileane|Rev.Ileane|
|  4| Rev.|12_Jeffry|Rev.Jeffry|
|  5|  Ms.|  12_Aryn|   Ms.Aryn|
+---+-----+---------+----------+

"""

As you can see we have specified the number of characters to be replaced from the source column to be 3, three characters from the start position have been removed and here we have our solution.

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

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

These could be the possible reasons:

  1. To replace a one-column value with another
  2. To cover a column with another by replacing specific portions

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

  • Consider you have two gender columns an abbreviated one and an extended one for example (‘M’, ‘Male’) and (‘FM’, ‘Female’). You have asked to replace the column abbreviated column with the extended column.
  • Assume you were given a patients dataset, The dataset includes the patient’s title, and name with a prefixed date for example (‘Mr.’ ’12_Berne’), and you were asked to create a column called “title_name” with the “title” and “name” column by excluding the prefixed date from the “name” column for example (‘Mr.’, ’12_Berne’, ‘Mr.Berne’).

These are some the real-world example in which you might use the overlay() function to solve the problem.

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

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

  • 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
  • regexpr_replace(): used for replacing column values using regular expression.

Final Thoughts

In this article, we have learned about the PySpark overlay() method to replace column values with another column 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.

PySpark in Azure Databricks, as explained by Arud Seka Berne S on azurelib.com.

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.