How to use substring() function in PySpark Azure Databricks?

Are you looking to find out how to get a substring value of a column in PySpark Azure Databricks cloud or maybe you are looking for a solution, to get substring data using the index position of the column data in PySpark Databricks using the substring() 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 get substring data on both DataFrame and SQL expression using the substring() 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 understanding how to use the substring() function in PySpark.

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

  • Syntax of substring()
  • Substring on DataFrame
  • Substring using SQL expression

The Pyspark substring() function takes a column name, start position, and length.

Syntax:

substring(column_name, start_position, length)

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

The syntax is as follows:

substring(column_name, start_position, length)
Parameter NameRequiredDescription
column_nameYesIt represents the column name.
start_positionYesIt represents the starting position of the substring data.
lengthYesIt represents the length of data from the starting position.
Table 1: substring() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: substring()

Create a simple DataFrame

Let’s understand the use of the lit() 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 = [
    ("Boehm, Volkman and Homenick","2022-08-06"),
    ("Kshlerin Inc","2009-03-30"),
    ("Kreiger, Weber and Brakus","2005-06-07"),
    ("Adams-Lowe","2013-02-16"),
    ("O'Conner-Herman","2022-07-20")
]

df = spark.createDataFrame(data, schema=["name","started"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- name: string (nullable = true)
 |-- started: string (nullable = true)

+---------------------------+----------+
|name                       |started   |
+---------------------------+----------+
|Boehm, Volkman and Homenick|2022-08-06|
|Kshlerin Inc               |2009-03-30|
|Kreiger, Weber and Brakus  |2005-06-07|
|Adams-Lowe                 |2013-02-16|
|O'Conner-Herman            |2022-07-20|
+---------------------------+----------+
"""

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

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

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

Let’s see how to get or fetch specific data from a column using substring() in Azure Databricks. Note: The substring index of the column value starts at 1.

Example 1:

# Using select

from pyspark.sql.functions import substring

df.select(
    "*",
    substring("started", 1, 4).alias("year"),
    substring("started", 6, 2).alias("month"),
    substring("started", 9, 2).alias("date")
).show(truncate=False)

"""
Output:

+---------------------------+----------+----+-----+----+
|name                       |started   |year|month|date|
+---------------------------+----------+----+-----+----+
|Boehm, Volkman and Homenick|2022-08-06|2022|08   |06  |
|Kshlerin Inc               |2009-03-30|2009|03   |30  |
|Kreiger, Weber and Brakus  |2005-06-07|2005|06   |07  |
|Adams-Lowe                 |2013-02-16|2013|02   |16  |
|O'Conner-Herman            |2022-07-20|2022|07   |20  |
+---------------------------+----------+----+-----+----+


"""

Example 2:

# Using withColumn

from pyspark.sql.functions import substring

df \
.withColumn("year", substring("started", 1, 4)) \
.withColumn("month", substring("started", 6, 2)) \
.withColumn("date", substring("started", 9, 2)) \
.show(truncate=False)

"""
Output:

+---------------------------+----------+----+-----+----+
|name                       |started   |year|month|date|
+---------------------------+----------+----+-----+----+
|Boehm, Volkman and Homenick|2022-08-06|2022|08   |06  |
|Kshlerin Inc               |2009-03-30|2009|03   |30  |
|Kreiger, Weber and Brakus  |2005-06-07|2005|06   |07  |
|Adams-Lowe                 |2013-02-16|2013|02   |16  |
|O'Conner-Herman            |2022-07-20|2022|07   |20  |
+---------------------------+----------+----+-----+----+

"""

How to get a portion of a column value in PySpark Azure Databricks using SQL expression?

Let’s see how to get or fetch specific data from a column using SQL expression in Azure Databricks. Note: The substring index of the column value starts at 1.

Example:

In order to use raw SQL expression in PySpark, we have to convert DataFrame to SQL View.

df.createOrReplaceTempView("company")

spark.sql("""
SELECT
    name,
    SUBSTRING(started, 1,4) AS year,
    SUBSTRING(started, 6,2) AS month,
    SUBSTRING(started, 9,2) AS date
FROM company""").show(truncate=False)

"""
Output:

+---------------------------+----+-----+----+
|name                       |year|month|date|
+---------------------------+----+-----+----+
|Boehm, Volkman and Homenick|2022|08   |06  |
|Kshlerin Inc               |2009|03   |30  |
|Kreiger, Weber and Brakus  |2005|06   |07  |
|Adams-Lowe                 |2013|02   |16  |
|O'Conner-Herman            |2022|07   |20  |
+---------------------------+----+-----+----+


"""

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

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

You should use the PySpark substring() function to extract a portion of string column values by mentioning the start and end index positions.

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

Assume that have a people name list and create a logo with the first letter of each one’s account name, you were asked to extract or get the first letter of their name. For example “Berne” to “B”. The PySpark substring() function helps in extracting the values by mentioning the index position.

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

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

  • Column.substr(): a column string function as same as the substring() function.
  • 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.
  • overlay(): used for replacing a source column with replacing column value starting from a position and proceeding for length.

Final Thoughts

In this article, we have learned about the PySpark substring() method to get or fetch a column-specific value 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.