How to concat multiple columns in PySparkAzure Databricks?

Are you looking to find out how to concat the ArrayType column of PySpark DataFrame into StringType column with a separator in Azure Databricks cloud or maybe you are looking for a solution, to concat with a separtor multiple columns into a single StringType column of PySpark Databricks using the concat_ws() 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 concat columns with separators on both dataframe and SQL expression using the concat_ws() 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 concat columns with separators in PySpark using the concat_ws() function.

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

  • Syntax of concat_ws()
  • Concat array column into string column with separator
  • Concat multiple columns into single column with separator

concat_ws() function takes, separator value and array column or multiple column name as string as arguments.

Syntax:

concat_ws(separator, *columns)

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

The syntax is as follows:

concat_ws(separator, *columns)
Parameter NameRequiredDescription
separatorYesIt represents the delimiter of the concat value.
columnsYesIt represents the concating columns.
Table 1: concat_ws() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: concat_ws()

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 = [
    (1, "Andie", "Ebbutt", ['Andie', 'Ebbutt']),
    (2, "Hobie", "Deegan", ['Hobie', 'Deegan']),
    (3, "Denys", "Belverstone", ['Denys', 'Belverstone']),
    (4, "Delphine", "Pietersma", ['Delphine', 'Pietersma']),
    (5, "Putnem", "Chasson", ['Putnem', 'Chasson'])
]

df = spark.createDataFrame(data, schema=["id", "f_name", "l_name", "name_list"])
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- f_name: string (nullable = true)
 |-- l_name: string (nullable = true)
 |-- name_list: array (nullable = true)
 |    |-- element: string (containsNull = true)

+---+--------+-----------+---------------------+
|id |f_name  |l_name     |name_list            |
+---+--------+-----------+---------------------+
|1  |Andie   |Ebbutt     |[Andie, Ebbutt]      |
|2  |Hobie   |Deegan     |[Hobie, Deegan]      |
|3  |Denys   |Belverstone|[Denys, Belverstone] |
|4  |Delphine|Pietersma  |[Delphine, Pietersma]|
|5  |Putnem  |Chasson    |[Putnem, Chasson]    |
+---+--------+-----------+---------------------+
"""

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("json").load(file_path)
df_2.printSchema()

"""
root
 |-- id: long (nullable = true)
 |-- f_name: string (nullable = true)
 |-- l_name: string (nullable = true)
 |-- name_list: array (nullable = true)
 |    |-- element: string (containsNull = true)
"""

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

How to concat ArrayType column with a separator in PySpark Azure Databricks?

Let’s see how to concat the column of PySpark’s DataFrame using concat_ws() using various methods in Azure Databricks.

Example 1:

# Using concat_ws() with select

from pyspark.sql.functions import concat_ws

df.select(concat_ws(",", "name_list").alias("concat_1")).show()

"""
Output:

+------------------+
|          concat_1|
+------------------+
|      Andie,Ebbutt|
|      Hobie,Deegan|
| Denys,Belverstone|
|Delphine,Pietersma|
|    Putnem,Chasson|
+------------------+


"""

Example 2:

# Using concat_ws() with withColumn

from pyspark.sql.functions import concat_ws

df.withColumn(
    "concat_2",
    concat_ws("-", "name_list")
).select("concat_2").show()

"""
Output:

+------------------+
|          concat_2|
+------------------+
|      Andie-Ebbutt|
|      Hobie-Deegan|
| Denys-Belverstone|
|Delphine-Pietersma|
|    Putnem-Chasson|
+------------------+

"""

Example 3:

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

# Using concat_ws() on SQL expression:

df.createOrReplaceTempView("name_list")

spark.sql("SELECT CONCAT_WS('||', name_list) AS concat_3 FROM name_list").show()

"""
Output:

+-------------------+
|           concat_3|
+-------------------+
|      Andie||Ebbutt|
|      Hobie||Deegan|
| Denys||Belverstone|
|Delphine||Pietersma|
|    Putnem||Chasson|
+-------------------+


"""

How to concat multiple columns with a separator in PySpark Azure Databricks?

Let’s see how to concat multiple columns of PySpark’s DataFrame using concat_ws() using various methods in Azure Databricks.

Example 1:

# Using concat_ws() with select

from pyspark.sql.functions import concat_ws

df.select(concat_ws(",", "id", "f_name").alias("concat_1")).show()

"""
Output:

+----------+
|  concat_1|
+----------+
|   1,Andie|
|   2,Hobie|
|   3,Denys|
|4,Delphine|
|  5,Putnem|
+----------+


"""

Example 2:

# Using concat_ws() with withColumn

from pyspark.sql.functions import concat_ws

df.withColumn(
    "concat_2",
    concat_ws("-", "id", "f_name")
).select("concat_2").show()

"""
Output:

+----------+
|  concat_2|
+----------+
|   1-Andie|
|   2-Hobie|
|   3-Denys|
|4-Delphine|
|  5-Putnem|
+----------+

"""

Example 3:

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

# Using concat_ws() on SQL expression:

df.createOrReplaceTempView("name_list")

spark.sql("""SELECT CONCAT_WS('||', id, f_name) AS concat_3 FROM name_list""").show()

"""
Output:

+-----------+
|   concat_3|
+-----------+
|   1||Andie|
|   2||Hobie|
|   3||Denys|
|4||Delphine|
|  5||Putnem|
+-----------+


"""

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 concat_ws() in Azure Databricks?

These could be the possible reasons:

  1. To contact multiple columns with a separator
  2. To contact ArrayType columns with a separator

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

  • Assume that you have been asked to create a column called ‘full_name’ by joining two ‘first_name’ and ‘last_name’ columns together. For example (‘Randy’, ‘Orton’) into (‘Randy’, ‘Orton’, ‘Randy Orton’). You can achieve this by passing the separator a space argument and the two column names.
  • Assume you have a candidate dataset. The dataset includes the candidate’s ID, name, and preferences in an ArrayType column for example (1, ‘Berne’, [‘Chennai’, ‘Bangalore’, ‘Kochin’]). You have been asked to contact these column values into a comma separate value for example (1, ‘Berne’, ‘Chennai, Bangalore, Kochin’). You can use the concat_ws() function to achieve this result.

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

There are alternatives to the concat_ws() function:

  • For joining columns use the lit() with concat() function together.

Final Thoughts

In this article, we have learned about the PySpark concat_ws() method to concat array type columns and multiple columns into single string type columns 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.