How to convert DataFrame to RDD in PySpark Azure Databricks?

Are you looking to find out how to convert DataFrame to RDD in PySpark Azure Databricks cloud or maybe you are looking for a solution, to find a method to convert PySpark RDD into DataFrame? 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 the RDD function in PySpark 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 convert DataFrame into RDD in PySpark Azure Databricks.

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

  • Convert DataFrame to RDD
  • RDD function
  • Convert RDD to DataFrame

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

data = [
    ("Mamie","Treharne"),
    ("Erv","Colam"),
    ("Daren","Salliss"),
    ("Vania","Laundon"),
    ("Jay","Kees")
]

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

"""
root
 |-- f_name: string (nullable = true)
 |-- l_name: string (nullable = true)

+------+--------+
|f_name|l_name  |
+------+--------+
|Mamie |Treharne|
|Erv   |Colam   |
|Daren |Salliss |
|Vania |Laundon |
|Jay   |Kees    |
+------+--------+
"""

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.

df_2 = spark.read.format("csv").option("header", True).load(file_path)
df_2.printSchema()

"""
root
 |-- f_name: string (nullable = true)
 |-- l_name: string (nullable = true)
"""

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

How to convert DataFrame into RDD in PySpark using Azure Databricks?

In this section, let’s see how to convert DataFrame into RDD in PySpark using Azure Databricks.

The dataFrameObject.rdd is used for converting PySpark DataFrame into RDD. Let me provide an example.

Example:

rdd = df.rdd
print(type(rdd)) # <- Checks the type of rdd variable
rdd.collect()

"""
Output:

<class 'pyspark.rdd.RDD'>

[
Row(f_name='Mamie', l_name='Treharne'),
 Row(f_name='Erv', l_name='Colam'),
 Row(f_name='Daren', l_name='Salliss'),
 Row(f_name='Vania', l_name='Laundon'),
 Row(f_name='Jay', l_name='Kees')
]

"""

How to use functions on RDD in PySpark Azure Databricks?

Let’s look at how to use functions on RDD in PySpark Azure Databricks in this section. Let’s get familiar with the RDD functions by solving a problem. Let’s try to print the first name and its length using the map function.

Example:

rdd1 = rdd.map(lambda tup: (tup[0], len(tup[0])))
rdd1.collect()

"""
Output:

[('Mamie', 5), ('Erv', 3), ('Daren', 5), ('Vania', 5), ('Jay', 3)]

"""

The map is an RDD function that is not available in PySpark DataFrame. Consider the map function just like a for loop, which iterates our every record.

How to convert RDD into DataFrame in PySpark using Azure Databricks?

In this section, let’s see how to convert RDD into DataFrame in PySpark using Azure Databricks. The PySpark map() function helps in converting the RDD into DataFrame, let me provide an example.

Example:

rdd1.toDF(["f_name", "len_name"]).show()

"""
Output:

+------+--------+
|f_name|len_name|
+------+--------+
| Mamie|       5|
|   Erv|       3|
| Daren|       5|
| Vania|       5|
|   Jay|       3|
+------+--------+

"""

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 convert DataFrame into RDD in PySpark using Azure Databricks?

These could be the possible reasons:

  1. For using RDD’s map() transformation
  2. For using RDD’s flatMap() transformation

Real World Use Case Scenarios for converting DataFrame into RDD in PySpark Azure Databricks?

Assume you have a huge DataFrame and you want the RDD’s map() or flatMap() functions to perform certain things. In this scenario you can go for converting DataFrame into RDD>

What are the alternatives for converting DataFrame into RDD in PySpark using Azure Databricks?

There are multiple alternatives for converting a DataFrame into an RDD in PySpark, which are as follows:

  • You can use the DataFrame.rdd for converting DataFrame into RDD.
  • You can collect the DataFrame and use parallelize() use can convert DataFrame into RDD.

Final Thoughts

In this article, we have learned about how to convert DataFrame into RDD 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.

PySpark in Azure Databricks, as explained by Arud Seka Berne S on azurelib.com.

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.