In this tutorial, we want to concatenate multiple PySpark DataFrames. In order to do this, we use the the union() method of PySpark.

Import Libraries

First, we import the following python modules:

from pyspark.sql import SparkSession

Create SparkSession

Before we can work with Pyspark, we need to create a SparkSession. A SparkSession is the entry point into all functionalities of Spark.

In order to create a basic SparkSession programmatically, we use the following command:

spark = SparkSession \
    .builder \
    .appName("Python PySpark Example") \

Create PySpark DataFrames

We create two PySpark DataFrames with some example data from lists. To do this, we use the method createDataFrame() and pass the data and the column names as arguments.

First, we create the PySpark DataFrame "df1":

column_names = ["language", "framework", "users"]
data = [
    ("Python", "FastAPI", 9000),
    ("JavaScript", "ReactJS", 7000),
df1 = spark.createDataFrame(data, column_names)

Next, we create the PySpark DataFrame "df2". The DataFrame has exactly the same schema like DataFrame "df1":

column_names = ["language", "framework", "users"]
data = [
    ("Python", "FastAPI", 9000),
    ("Python", "Django", 20000),
    ("Java", "Spring", 12000),
df2 = spark.createDataFrame(data, column_names)

Concatenate DataFrames

Now, we would like to concatenate the DataFrames "df1" and "df2".

You can view this post with the tier: Academy Membership

Join academy now to read the post and get access to the full library of premium posts for academy members only.

Join Academy Already have an account? Sign In