How to rename DataFrame columns in PySpark Azure Databricks?

Are you looking to find how to rename the column of a PySpark DataFrame in an Azure Databricks cloud or maybe you are looking for a solution, to change the DataFrame existing column name into a new column name in PySpark Databricks using the withColumnRenamed() method? If you are looking for any of these problem solutions, then you have landed on the correct page. I will also show you how to use PySpark to rename the column name of a DataFrame in 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 PySpark DataFrame.

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

  • Syntax of withColumnRenamed()
  • Renaming Single column
  • Renaming multiple columns
  • Renaming entire columns

withColumnRenamed() method used to rename the column of the DataFrame in PySpark Azure Databricks.

Syntax: dataframe_name.withColumnRenamed(old_column_name, new_column_name)

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

The syntax is as follows:

dataframe_name.withColumnRenamed(existing, new)
Parameter NameRequiredDescription
existing (str)YesIt represents the name of the existing column to rename.
new (str)YesIt represents the new name of the column.
Table 1: withColumnRenamed() Method in PySpark Databricks Parameter list with Details

Official Apache Spark documentation link: withColumnRenamed()

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 = [    
    (1,"Fleurette","Nevada"),
    (2,"Carmel","California"),
    (3,"Dore","Texas"),
    (4,"Field","California"),
    (5,"Harcourt","Arizona")
]

df = spark.createDataFrame(data, schema=["id","name","state"])
df.printSchema()
df.show()

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

+---+---------+----------+
| id|     name|     state|
+---+---------+----------+
|  1|Fleurette|    Nevada|
|  2|   Carmel|California|
|  3|     Dore|     Texas|
|  4|    Field|California|
|  5| Harcourt|   Arizona|
+---+---------+----------+
"""

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
 |-- id: long (nullable = true)
 |-- name: string (nullable = true)
 |-- state: string (nullable = true)
"""

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

How to rename a single column in PySpark Azure Databricks?

By providing the existing and new column names to the withColumnRenamed() function, you can rename the column name from the DataFrame. This generates a new DataFrame with the chosen columns because DataFrame is immutable. To rename the column of DataFrame, use the withColumnRenamed() function.

Example:

df.withColumnRenamed("name", "student_name").show()

"""
Output:

+---+------------+----------+
| id|student_name|     state|
+---+------------+----------+
|  1|   Fleurette|    Nevada|
|  2|      Carmel|California|
|  3|        Dore|     Texas|
|  4|       Field|California|
|  5|    Harcourt|   Arizona|
+---+------------+----------+

"""

How to rename multiple columns in PySpark Azure Databricks?

To rename the multiple columns of DataFrame, use the withColumnRenamed() function on top of the existing DataFrame.

Example:

df \
.withColumnRenamed("id", "student_id") \
.withColumnRenamed("name", "student_name") \
.show()

"""
Output:

+----------+------------+----------+
|student_id|student_name|     state|
+----------+------------+----------+
|         1|   Fleurette|    Nevada|
|         2|      Carmel|California|
|         3|        Dore|     Texas|
|         4|       Field|California|
|         5|    Harcourt|   Arizona|
+----------+------------+----------+

"""

How to rename entire column in PySpark Azure Databricks using the toDF() function?

To rename the entire column we can use the toDF() function for renaming it. Let’s see this with a practical example.

Example:

df.toDF("student_id", "student_name", "student_address").show()

"""
Output:

+----------+------------+---------------+
|student_id|student_name|student_address|
+----------+------------+---------------+
|         1|   Fleurette|         Nevada|
|         2|      Carmel|     California|
|         3|        Dore|          Texas|
|         4|       Field|     California|
|         5|    Harcourt|        Arizona|
+----------+------------+---------------+

"""

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

In Spark withColumnRenamed() is used to rename one column or multiple DataFrame column names. Depending on the DataFrame schema, renaming columns might get simple to complex, especially when a column is nested with struct type it gets complicated.

  1. When you want to change the column name in a dataframe.

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

  • You read the file as the dataframe. However the name of the column in header contains space and you want to replace that name with new column name. Then this function can be very handy to use at that place.
  • You are about to join two tables and to avoid the duplicate column name after join operation, you can rename the common column using the withCOlumnRename function.

What are the alternatives of the withColumnRenamed() function in PySpark Azure Databricks?

There are multiple alternatives of the withColumnRenamed() function, which are as follows:

Use the toDF() function in PySpark to rename the column accordingly.

Example:

df.toDF("student_id", "student_name", "student_address").show()

"""
Output:

+----------+------------+---------------+
|student_id|student_name|student_address|
+----------+------------+---------------+
|         1|    Mahesh R|    Tirunelveli|
|         2|    Nandhu S|     Coimbatore|
|         3|    Roshan P|          Salem|
+----------+------------+---------------+

"""

Final Thoughts

In this article, we have learned about the PySpark withColumnRenamed() method to rename the columns 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.