Are you looking to find out how to change the struct of the existing DataFrame and add a new StructType to it in PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to extract the MapType column unique values into a python list of PySpark Databricks using the map_values() 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 struct() 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 struct() function in PySpark.
In this blog, I will teach you the following with practical examples:
- Syntax of struct() function
- Creating new struct out of existing column
The Pyspark struct() function is used to create new struct column.
Syntax:
struct()
Contents
- 1 What is the syntax of the struct() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to add or change struct of PySpark DataFrame using Azure Databricks?
- 4 When should you use the PySpark struct() in Azure Databricks?
- 5 Real World Use Case Scenarios for PySpark DataFrame struct() in Azure Databricks?
- 6 What are the alternatives to the struct() function in PySpark Azure Databricks?
- 7 Final Thoughts
What is the syntax of the struct() function in PySpark Azure Databricks?
The syntax is as follows:
struct(*columns)
Parameter Name | Required | Description |
columns (list, set, str or Column) | Yes | It represents the column name to contain in the output struct. |
Apache Spark Official Documentation Link: struct()
Create a simple DataFrame
Let’s understand the use of the struct() 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 = [
("Mamie","Treharne"),
("Erv","Colam"),
("Daren","Salliss"),
("Vania","Laundon"),
("Jay","Kees"),
]
df = spark.createDataFrame(data, schema=["f_name","l_name"])
df.printSchema()
df.show(5, 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_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
|-- f_name: string (nullable = true)
|-- l_name: string (nullable = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to add or change struct of PySpark DataFrame using Azure Databricks?
Let’s see how to add or change the struct of PySpark DataFrame in Azure Databricks using various methods.
Example 1:
# Using select()
from pyspark.sql.functions import struct, col
# Method 1:
df_3 = df.select(struct("f_name", "l_name").alias("name"))
# Method 2:
df_3 = df.select(struct(["f_name", "l_name"]).alias("name"))
# Method 3:
df_3 = df.select(struct([col("f_name"), col("l_name")]).alias("name"))
# Method 4:
columns = ("f_name", "l_name")
df_3 = df.select(struct(*columns).alias("name"))
df_3.printSchema()
df_3.show()
"""
Output:
root
|-- name: struct (nullable = false)
| |-- f_name: string (nullable = true)
| |-- l_name: string (nullable = true)
+-----------------+
| name|
+-----------------+
|{Mamie, Treharne}|
| {Erv, Colam}|
| {Daren, Salliss}|
| {Vania, Laundon}|
| {Jay, Kees}|
+-----------------+
"""
Example 2:
# Using withColumn()
from pyspark.sql.functions import struct
df_4 = df.withColumn("name", struct("f_name", "l_name"))
df_4.show()
"""
Output:
+------+--------+-----------------+
|f_name| l_name| name|
+------+--------+-----------------+
| Mamie|Treharne|{Mamie, Treharne}|
| Erv| Colam| {Erv, Colam}|
| Daren| Salliss| {Daren, Salliss}|
| Vania| Laundon| {Vania, Laundon}|
| Jay| Kees| {Jay, Kees}|
+------+--------+-----------------+
"""
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 struct() in Azure Databricks?
These could be the possible reasons:
- To change the column structure of the existing column
- To add a new structure to an existing column
Real World Use Case Scenarios for PySpark DataFrame struct() in Azure Databricks?
Assume that you were given two columns and what to change column values from a flat structure to a nested column structure. You can use the PySpark struct() function to alter or change its structure of it from flat to nested structure. For example, converting first_name and last_name into name.first_name and name.last_name from existing column.
What are the alternatives to the struct() function in PySpark Azure Databricks?
The only way of converting or altering column structure into struct type is by using the struct() function and this function is explained with an example in the above section.
Final Thoughts
In this article, we have learned about the PySpark struct() 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.
- For Azure Study material Join Telegram group : Telegram group link:
- Azure Jobs and other updates Follow me on LinkedIn: Azure Updates on LinkedIn
- Azure Tutorial Videos: Videos Link
- Azure Databricks Lesson 1
- Azure Databricks Lesson 2
- Azure Databricks Lesson 3
- Azure Databricks Lesson 4
- Azure Databricks Lesson 5
- Azure Databricks Lesson 6
- Azure Databricks Lesson 7
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.