Are you looking to find out how to join multiple columns in PySpark Azure Databricks cloud or maybe you are looking for a solution, to join two DataFrames on multiple columns without duplication? 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 both PySpark and Spark SQL way of doing a multiple-column join in Azure Databricks. I will explain it with a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to join multiple columns in PySpark Azure Databricks.
In this blog, I will teach you the following with practical examples:
- Syntax of join()
- Joining multiple columns
- Joining multiple columns using where()
- Eliminate duplicate columns while joining DataFrames
- Multiple column join SQL expression
join() method is used to join two Dataframes together based on condition specified in PySpark Azure Databricks.
Syntax: dataframe_name.join()
Contents
- 1 What is the syntax of the join() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to join multiple columns in PySpark Azure Databricks?
- 4 How to join multiple columns in PySpark Azure Databricks using the where() function?
- 5 How to remove duplicate columns while joining DataFrames in PySpark Azure Databricks?
- 6 How to join multiple columns in PySpark Azure Databricks using SQL expression?
- 7 When should you use multiple column join in PySpark using Azure Databricks?
- 8 Real World Use Case Scenarios for using multiple columns join in PySpark Azure Databricks?
- 9 What are the alternatives for multiple-column joining in PySpark using Azure Databricks?
- 10 Final Thoughts
What is the syntax of the join() function in PySpark Azure Databricks?
The syntax is as follows:
dataframe_name.join(other, on, how)
Parameter Name | Required | Description |
other (Dataframe) | Yes | It represents the second column to be joined. |
on (str, list, or Column) | Yes | A string for the join column name, a list of column names, a join expression (Column), or a list of Columns. If on is a string or a list of strings indicating the name of the join column(s), the column(s) must exist on both sides. |
how (str) | Optional | It represents join type, by default how=”inner”. |
Apache Spark Official documentation link: join()
Create a simple 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
# 1. Student Dataset
student_data = [
(1,"Karee",1,"A"),
(2,"Jobie",2,"B"),
(3,"Kyle",3,"A"),
(4,"Georges",1,"B"),
(5,"Tracey",2,"A")
]
std_df = spark.createDataFrame(student_data, schema=["id","name","dept_id","section"])
std_df.printSchema()
std_df.show(truncate=False)
"""
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- dept_id: long (nullable = true)
|-- section: string (nullable = true)
+---+-------+-------+-------+
|id |name |dept_id|section|
+---+-------+-------+-------+
|1 |Karee |1 |A |
|2 |Jobie |2 |B |
|3 |Kyle |3 |A |
|4 |Georges|1 |B |
|5 |Tracey |2 |A |
+---+-------+-------+-------+
"""
# 2. Department Dataset
dept_data = [
(1,"civil","A",301),
(1,"civil","B",302),
(2,"mech","A",401),
(2,"mech","B",402),
(3,"ece","A",501),
(3,"ece","B",502)
]
columns = ["dept_id","dept_name","section","hall_no"]
dept_df = spark.createDataFrame(data = dept_data, schema=columns)
dept_df.printSchema()
dept_df.show(truncate=False)
"""
root
|-- dept_id: long (nullable = true)
|-- dept_name: string (nullable = true)
|-- section: string (nullable = true)
|-- hall_no: long (nullable = true)
+-------+---------+-------+-------+
|dept_id|dept_name|section|hall_no|
+-------+---------+-------+-------+
|1 |civil |A |301 |
|1 |civil |B |302 |
|2 |mech |A |401 |
|2 |mech |B |402 |
|3 |ece |A |501 |
|3 |ece |B |502 |
+-------+---------+-------+-------+
"""
b) Creating a DataFrame by reading files
Download and use the below source file.
# replace the file_paths with the source file location which you have downloaded.
std_df_2 = spark.read.format("csv").option("header", True).load(student_file_path)
std_df_2.printSchema()
dept_df_2 = spark.read.format("csv").option("header", True).load(department_file_path)
dept_df_2.printSchema()
"""
root
|-- id: long (nullable = true)
|-- name: string (nullable = true)
|-- dept_id: long (nullable = true)
|-- section: string (nullable = true)
root
|-- dept_id: long (nullable = true)
|-- dept_name: string (nullable = true)
|-- section: string (nullable = true)
|-- hall_no: long (nullable = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to join multiple columns in PySpark Azure Databricks?
Before joining DataFrames based on multiple columns, let’s discuss a bit about the dataset we have. We have a student dataset that includes their id, name, department id, and section. We have a department dataset with the department id, name, section, and hall number. Now, let’s try joining both DataFrames using multiple columns and display each student and their hall number.
Example:
Note: In order to join DataFrames based on multiple conditions, multiple join conditions has been specified.
# 1. Multiple join
multiple_join_condition = (std_df.dept_id == dept_df.dept_id) & (std_df.section == dept_df.section)
std_dept_df = std_df.join(dept_df, multiple_join_condition , how="inner")
# 2. How to select a duplicate column
std_dept_df.select("id","name", "dept_name", dept_df.section, "hall_no").show()
"""
Output:
+---+-------+---------+-------+-------+
| id| name|dept_name|section|hall_no|
+---+-------+---------+-------+-------+
| 1| Karee| civil| A| 301|
| 4|Georges| civil| B| 302|
| 5| Tracey| mech| A| 401|
| 2| Jobie| mech| B| 402|
| 3| Kyle| ece| A| 501|
+---+-------+---------+-------+-------+
"""
Remember, always specific condition inside ‘()’ brackets, because ‘=='
has lower precedence than bitwise AND
and OR
.
Since we have duplicate columns in the std_dept_df DataFrame, we can’t call straight away, which leads to an error. Therefore, we have used the department DataFrame to call the specific column.
How to join multiple columns in PySpark Azure Databricks using the where() function?
In this section, let’s see how to join multiple columns using the where() function in PySpark Azure Databricks by solving the above-mentioned problem.
Example:
# 1. Multiple join using where
first_condition = std_df.dept_id == dept_df.dept_id
second_condition = std_df.section == dept_df.section
std_dept_df_2 = std_df.join(dept_df, first_condition, how="inner") # <- first condition in join()
std_dept_df_2 = std_dept_df_2.where(second_condition) # <- Second condition in where() or filter()
# 2. How to select a duplicate column
std_dept_df_2.select("id","name", "dept_name", dept_df.section, "hall_no").show()
"""
Output:
+---+-------+---------+-------+-------+
| id| name|dept_name|section|hall_no|
+---+-------+---------+-------+-------+
| 1| Karee| civil| A| 301|
| 5| Tracey| mech| A| 401|
| 3| Kyle| ece| A| 501|
| 4|Georges| civil| B| 302|
| 2| Jobie| mech| B| 402|
+---+-------+---------+-------+-------+
"""
In this example, we have specified two joining conditions, by applying the first condition in the join() function and the second condition in the where() function.
How to remove duplicate columns while joining DataFrames in PySpark Azure Databricks?
In this section, let’s see how to remove duplicate columns while joining DataFrames in PySpark Azure Databricks with an example.
Example:
std_df.join(dept_df, ["dept_id", "section"], how="inner").show()
"""
Output:
+-------+-------+---+-------+---------+-------+
|dept_id|section| id| name|dept_name|hall_no|
+-------+-------+---+-------+---------+-------+
| 1| A| 1| Karee| civil| 301|
| 1| B| 4|Georges| civil| 302|
| 2| A| 5| Tracey| mech| 401|
| 2| B| 2| Jobie| mech| 402|
| 3| A| 3| Kyle| ece| 501|
+-------+-------+---+-------+---------+-------+
"""
In this example, we have no duplicate columns in the output DataFrame. By specifying the column names in array format, we can remove the duplicate columns.
How to join multiple columns in PySpark Azure Databricks using SQL expression?
In this section, let’s try to join multiple columns using student and department datasets using SQL expressions. In order to use a raw SQL expression, we have to convert our DataFrame into a SQL view.
std_df.createOrReplaceTempView("student")
dept_df.createOrReplaceTempView("department")
Example 1:
# 1. With duplicate joining columns
spark.sql('''
SELECT *
FROM student AS std
JOIN department AS dept
ON std.dept_id = dept.dept_id AND std.section = dept.section
''').show()
"""
Output:
+---+-------+-------+-------+-------+---------+-------+-------+
| id| name|dept_id|section|dept_id|dept_name|section|hall_no|
+---+-------+-------+-------+-------+---------+-------+-------+
| 1| Karee| 1| A| 1| civil| A| 301|
| 4|Georges| 1| B| 1| civil| B| 302|
| 5| Tracey| 2| A| 2| mech| A| 401|
| 2| Jobie| 2| B| 2| mech| B| 402|
| 3| Kyle| 3| A| 3| ece| A| 501|
+---+-------+-------+-------+-------+---------+-------+-------+
"""
Example 2:
# 2: Without duplicate joining columns
spark.sql('''
SELECT *
FROM student AS std
JOIN department AS dept
USING (dept_id, section)
''').show()
"""
Output:
+-------+-------+---+-------+---------+-------+
|dept_id|section| id| name|dept_name|hall_no|
+-------+-------+---+-------+---------+-------+
| 1| A| 1| Karee| civil| 301|
| 1| B| 4|Georges| civil| 302|
| 2| A| 5| Tracey| mech| 401|
| 2| B| 2| Jobie| mech| 402|
| 3| A| 3| Kyle| ece| 501|
+-------+-------+---+-------+---------+-------+
"""
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 multiple column join in PySpark using Azure Databricks?
This could be the possible reason:
To extract all the Left DataFrame and Right DataFrame records based n multiple columns matching values.
Real World Use Case Scenarios for using multiple columns join in PySpark Azure Databricks?
Assume that you have a student and department data set. The student dataset has the student id, name, department id, and section. And the department dataset has the id, name, section, and hall number. Now, you were given a requirement to combine both DataFrames to show student’s hall numbers to avoid classroom confusion. You can those techniques mentioned in the above section to achieve the requirement.
What are the alternatives for multiple-column joining in PySpark using Azure Databricks?
There are multiple alternatives for multiple-column joining in PySpark DataFrame, which are as follows:
- DataFrame.join(): used for combining DataFrames
- Using PySpark SQL expressions
Final Thoughts
In this article, we have learned about how to join multiple columns in PySpark 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.
- For Azure Study material Join Telegram group : Telegram group link:
- Azure Jobs and other updates Follow me on LinkedIn: Azure Updates on LinkedIn
- Azure Tutorial Videos: Videos Link
- Azure Databricks Lesson 1
- Azure Databricks Lesson 2
- Azure Databricks Lesson 3
- Azure Databricks Lesson 4
- Azure Databricks Lesson 5
- Azure Databricks Lesson 6
- Azure Databricks Lesson 7
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.