Do a Left Join in PySpark (With Example)


You can use the following basic syntax to perform a left join in PySpark:

df_joined = df1.join(df2, on=['team'], how='left').show()

This particular example will perform a left join using the DataFrames named df1 and df2 by joining on the column named team.

All rows from df1 will be returned in the final DataFrame but only the rows from df2 that have a matching value in the team column will be returned.

The following example shows how to use this syntax in practice.

Example: How to Do a Left Join in PySpark

Suppose we have the following DataFrame named df1:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

#define data
data1 = [['Mavs', 11], 
       ['Hawks', 25], 
       ['Nets', 32], 
       ['Kings', 15],
       ['Warriors', 22],
       ['Suns', 17]]

#define column names
columns1 = ['team', 'points'] 
  
#create dataframe using data and column names
df1 = spark.createDataFrame(data1, columns1) 
  
#view dataframe
df1.show()

+--------+------+
|    team|points|
+--------+------+
|    Mavs|    11|
|   Hawks|    25|
|    Nets|    32|
|   Kings|    15|
|Warriors|    22|
|    Suns|    17|
+--------+------+

And suppose we have another DataFrame named df2:

#define data
data2 = [['Mavs', 4], 
       ['Nets', 7], 
       ['Suns', 8], 
       ['Grizzlies', 12],
       ['Kings', 7]]

#define column names
columns2 = ['team', 'assists'] 
  
#create dataframe using data and column names
df2 = spark.createDataFrame(data2, columns2) 
  
#view dataframe
df2.show()

+---------+-------+
|     team|assists|
+---------+-------+
|     Mavs|      4|
|     Nets|      7|
|     Suns|      8|
|Grizzlies|     12|
|    Kings|      7|
+---------+-------+

We can use the following syntax to perform a left join between these two DataFrames by joining on values from the team column:

#perform left join using 'team' column
df_joined = df1.join(df2, on=['team'], how='left').show()

+--------+------+-------+
|    team|points|assists|
+--------+------+-------+
|    Mavs|    11|      4|
|   Hawks|    25|   null|
|    Nets|    32|      7|
|   Kings|    15|      7|
|Warriors|    22|   null|
|    Suns|    17|      8|
+--------+------+-------+

Notice that the resulting DataFrame contains all rows from the left DataFrame (df1) but only the rows from the right DataFrame (df2) that had a matching value in the team column.

Note that if the right DataFrame did not contain a matching team value for any team in the left DataFrame, a value of null is used in the assists column.

For example, the team name “Hawks” did not exist in df2, so this row received a value of null in the assists column of the final joined DataFrame.

x