How to create MapType column from existing columns in PySpark Azure Databricks?

Are you looking to find out how to create a column of MapType of PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to create a MapType column from existing column of PySpark Databricks using the create_function() function? If you are looking for any of these problem solutions, you have landed on the correct page. I will also help you how to use PySpark create_function() function with multiple examples in Azure Databricks. I will explain it by taking a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to use the create_function() function in PySpark.

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

  • Syntax of create_function() function
  • Creating a MapType column
  • Creating a custom key and value MapType column

The Pyspark create_map() function is used to create a new MapType column.

Syntax:

create_map()

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

The syntax is as follows:

create_map(*columns)
Parameter NameRequiredDescription
columns (str, Column)YesIt represents the column names or Columns that are grouped as key-value pairs.
For e.g. (key1, value1, key2, value2, …)
Table 1: create_map() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: create_map()

Create a simple DataFrame

Let’s understand the use of the create_map() function with a variety of examples. Let’s start by creating a 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 = [
    (1,"Waldemar",31),
    (2,"Abbey",19),
    (3,"Amalle",30),
    (4,"Uri",23),
    (5,"Dennie",58)
]

columns = ["id","name","age"]
df = spark.createDataFrame(data, schema=columns)
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- age: long (nullable = true)

+---+--------+---+
|id |name    |age|
+---+--------+---+
|1  |Waldemar|31 |
|2  |Abbey   |19 |
|3  |Amalle  |30 |
|4  |Uri     |23 |
|5  |Dennie  |58 |
+---+--------+---+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

# replace the file_path 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
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- age: long (nullable = true)
"""

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

How to create a MapType column in PySpark Azure Databricks?

Let’s see how to create a MapType column in PySpark Azure Databricks using various methods.

Example:

from pyspark.sql.functions import create_map, col

# Method 1:
df.select("*", create_map("name", "age")).show()

# Method 2:
df.select("*", create_map(["name", "age"])).show()

# Method 3:
df.select("*", create_map(col("name"), col("age"))).show()

# Method 4:
df.select("*", create_map([col("name"), col("age")])).show()

# The above codes generates the same output as mentioned below.

"""
Output:

+---+--------+---+----------------+
| id|    name|age|  map(name, age)|
+---+--------+---+----------------+
|  1|Waldemar| 31|{Waldemar -> 31}|
|  2|   Abbey| 19|   {Abbey -> 19}|
|  3|  Amalle| 30|  {Amalle -> 30}|
|  4|     Uri| 23|     {Uri -> 23}|
|  5|  Dennie| 58|  {Dennie -> 58}|
+---+--------+---+----------------+

"""

Let’s check the schema of the created DataFrame.

df.select("*", create_map([col("name"), col("age")])).printSchema()

"""
Output:

root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- age: long (nullable = true)
 |-- map(name, age): map (nullable = false)
 |    |-- key: string
 |    |-- value: long (valueContainsNull = true)

"""

How to create a MapType column with a custom key and value in PySpark Azure Databricks?

Let’s see how to create a MapType column with a custom key and value in PySpark Azure Databricks.

Example:

from pyspark.sql.functions import create_map, col, lit, concat

df_3 = df.select("*",  create_map(
    lit("emp_id"), concat(lit("EMP_"), col("id")),
    lit("age"), col("age")
).alias("properties"))

df_3.printSchema()
df_3.show(truncate=False)

"""
Output:

root
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- age: long (nullable = true)
 |-- properties: map (nullable = false)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)

+---+--------+---+----------------------------+
|id |name    |age|properties                  |
+---+--------+---+----------------------------+
|1  |Waldemar|31 |{emp_id -> EMP_1, age -> 31}|
|2  |Abbey   |19 |{emp_id -> EMP_2, age -> 19}|
|3  |Amalle  |30 |{emp_id -> EMP_3, age -> 30}|
|4  |Uri     |23 |{emp_id -> EMP_4, age -> 23}|
|5  |Dennie  |58 |{emp_id -> EMP_5, age -> 58}|
+---+--------+---+----------------------------+

"""

Note: In the above example, you can see that the number of arguments passed inside the create_map() function is even. Because create_map() expects a positive even number of arguments, the odd and even columns act as key and value respectively.

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

These could be the possible reasons:

  1. For creating new map columns from existing columns
  2. When you want to group multiple columns into a single MapType column

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

Assume that you were given a Pokémon dataset. The dataset contains the pokemon’s name, color, strength, protection, stamina, and rage. You might see that some of the columns can be grouped. For example, the columns strength, protection, stamina, and rage. These columns can be grouped under a column that may be a “level” column.

What are the alternatives to the create_map() function in PySpark Azure Databricks?

These alternatives were discussed with multiple examples in the above section.

  • Use the lit() function for creating a MapType column from a literal value
  • Use the from_json() function to create a MapType column from a JSON string

Final Thoughts

In this article, we have learned about the PySpark create_map() method of DataFrame 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.

Arud Seka Berne S

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.