How to use map() function in PySpark Azure Databricks?

Are you looking to find how to use map() function in PySpark RDD Azure Databricks cloud or maybe you are looking for a solution, to do a transformation using map() of Dataframe in PySpark Databricks using the map methods? If you are looking for any of these problem solutions, then you have landed on the correct page. I will also show you what and how to use the PySpark map() function in PySpark Azure Databricks. I will explain it with a practical example. So don’t waste time let’s start with a step-by-step guide to understanding how to select columns in a PySpark DataFrame.

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

  • Syntax of map()
  • Using the map() function on RDD
  • Using the map() function on DataFrame

map() is a transformation used to apply the transformation function (lambda) on every element of RDD/DataFrame and returns a new RDD.

Syntax: dataframe_name.map()

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

The syntax is as follows:

map(f, preservesPartitioning=False)
Parameter NameRequiredDescription
f (function)YesIt represents the function to be applied.
preservesPartitioning (bool)OptionalIt preserves partitioning.
Table 1: map() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: map()

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 = [    
    ("Binni","Trewin"),
    ("Tina","Wortt"),
    ("Ardisj","Larrett"),
    ("Cristobal","Gaunt"),
    ("Darline","Duigan")
]

# a. Creating an RDD
rdd = sc.parallelize(data)

# b. Creating a DataFrame
df = spark.createDataFrame(data, schema=["f_name", "_name"])
df.printSchema()
df.show()

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

+---------+-------+
|   f_name|  _name|
+---------+-------+
|    Binni| Trewin|
|     Tina|  Wortt|
|   Ardisj|Larrett|
|Cristobal|  Gaunt|
|  Darline| Duigan|
+---------+-------+
"""

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)
 |-- _name: string (nullable = true)
"""

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

How to use the map() function on RDD in PySpark Azure Databricks?

In the below example, we are trying to capitalize the first letter.

Example:

rdd.map(lambda name_tuple: (name_tuple[0].capitalize(), name_tuple[1].capitalize())).collect()

"""
Output:

[
('Binni', 'Trewin'),
 ('Tina', 'Wortt'),
 ('Ardisj', 'Larrett'),
 ('Cristobal', 'Gaunt'),
 ('Darline', 'Duigan')
]

"""

How to use the map() function on DataFrame in PySpark Azure Databricks?

Example:

df.rdd.map(lambda name_tuple: (name_tuple[0], name_tuple[1])) \
.toDF(["f_name", "l_name"]) \
.show()

"""
Output:

+---------+-------+
|   f_name| l_name|
+---------+-------+
|    Binni| Trewin|
|     Tina|  Wortt|
|   Ardisj|Larrett|
|Cristobal|  Gaunt|
|  Darline| Duigan|
+---------+-------+

"""

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 map() function PySpark in Azure Databricks?

Any sophisticated operations, such as adding a column, changing a column, modifying the data, etc., are applied using the map() transformation. The output of a map transformation will always contain the same number of records as the input.

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

Assume you have an RDD with first name and last name as input records, you want to create a new RDD by combining the row element, for example (“MS”, “Dhoni”) into (“MS Dhoni”). You can use the map() function to achieve this.

What are the alternative methods for iterating records in PySpark Azure Databricks?

There are multiple alternative methods for iterating records in PySpark Azure Databricks, which are as follows:

  • map() is a one-to-one operation which returns the record
  • flatMap() is a one-to-many operation that flattens all the collections into a single collection
  • foreach() is an iterating function but it would return anything

Final Thoughts

In this article, we have learned about the PySpark map() transformation 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.

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.