Built with Tutify.io

    AIStudyLabs

    DataFrame - Rename Column

    DataFrame - Rename Column

    Introduction

    In PySpark, 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.

    First, let’s create our data and DataFrame using PySpark.

    from pyspark.sql import SparkSession
    from pyspark.sql import Row
    from pyspark.sql.types import StructType, StructField, StringType, IntegerType
    
    spark = SparkSession.builder.appName("example").getOrCreate()
    
    data = [
        Row(Row("James", "", "Smith"), "36636", "M", 3000),
        Row(Row("Michael", "Rose", ""), "40288", "M", 4000),
        Row(Row("Robert", "", "Williams"), "42114", "M", 4000),
        Row(Row("Maria", "Anne", "Jones"), "39192", "F", 4000),
        Row(Row("Jen", "Mary", "Brown"), "", "F", -1)
    ]
    

    Our base schema with a nested structure.

    schema = StructType([
        StructField("name", StructType([
            StructField("firstname", StringType(), True),
            StructField("middlename", StringType(), True),
            StructField("lastname", StringType(), True)
        ]), True),
        StructField("dob", StringType(), True),
        StructField("gender", StringType(), True),
        StructField("salary", IntegerType(), True)
    ])
    

    Let’s create the DataFrame using the createDataFrame function and provide the above schema.

    df = spark.createDataFrame(data, schema)
    df.printSchema()
    

    Output:

    root
     |-- name: struct (nullable = true)
     |    |-- firstname: string (nullable = true)
     |    |-- middlename: string (nullable = true)
     |    |-- lastname: string (nullable = true)
     |-- dob: string (nullable = true)
     |-- gender: string (nullable = true)
     |-- salary: integer (nullable = true)
    

    1. Using withColumnRenamed() to Rename Column Name

    This is the most straightforward approach; this function takes two parameters: the first is your existing column name, and the second is the new column name you wish for.

    Syntax:

    DataFrame.withColumnRenamed(existingName, newName)
    

    existingName – The existing column name you want to change

    newName – New name of the column

    Returns a new DataFrame with a column renamed. This is a no-op if the schema doesn’t contain existingName.

    Example:

    df.withColumnRenamed("dob", "DateOfBirth").printSchema()
    

    Output:

    root
     |-- name: struct (nullable = true)
     |    |-- firstname: string (nullable = true)
     |    |-- middlename: string (nullable = true)
     |    |-- lastname: string (nullable = true)
     |-- DateOfBirth: string (nullable = true)
     |-- gender: string (nullable = true)
     |-- salary: integer (nullable = true)
    

    The above example changes the column name from “dob” to “DateOfBirth” on the PySpark DataFrame. Note that withColumnRenamed function returns a new DataFrame and doesn’t modify the current DataFrame.

    2. Rename Multiple Columns

    To change multiple column names, we should chain withColumnRenamed functions as shown below.

    df2 = df.withColumnRenamed("dob", "DateOfBirth")\
        .withColumnRenamed("salary", "salary_amount")
    df2.printSchema()
    

    Output:

    root
     |-- name: struct (nullable = true)
     |    |-- firstname: string (nullable = true)
     |    |-- middlename: string (nullable = true)
     |    |-- lastname: string (nullable = true)
     |-- DateOfBirth: string (nullable = true)
     |-- gender: string (nullable = true)
     |-- salary_amount: integer (nullable = true)
    

    This creates a new DataFrame “df2” after renaming dob and salary columns.

    3. Using StructType – To Rename a Nested Column in DataFrame

    Changing a column name on nested data is not straightforward, and we can do this by creating a new schema with new DataFrame columns using StructType and using it with the cast function as shown below.

    schema2 = StructType([
        StructField("fname", StringType(), True),
        StructField("middlename", StringType(), True),
        StructField("lname", StringType(), True)
    ])
    
    from pyspark.sql.functions import col
    
    df.select(col("name").cast(schema2), col("dob"), col("gender"), col("salary")).printSchema()
    

    Output:

    root
     |-- fname: string (nullable = true)
     |-- middlename: string (nullable = true)
     |-- lname: string (nullable = true)
     |-- dob: string (nullable = true)
     |-- gender: string (nullable = true)
     |-- salary: integer (nullable = true)
    

    This statement renames firstname to fname and lastname to lname within the name structure.

    4. Using select() to Rename Nested Elements

    Let’s see another way to change nested columns by transposing the structure to flat.

    df.select(
        col("name.firstname").alias("fname"),
        col("name.middlename").alias("mname"),
        col("name.lastname").alias("lname"),
        col("dob"), col("gender"), col("salary")
    ).printSchema()
    

    Output:

    root
     |-- fname: string (nullable = true)
     |-- mname: string (nullable = true)
     |-- lname: string (nullable = true)
     |-- dob: string (nullable = true)
     |-- gender: string (nullable = true)
     |-- salary: integer (nullable = true)
    

    5. Using withColumn() to Rename Nested Columns

    When you have nested columns on a PySpark DataFrame, and if you want to rename it, use withColumn on a DataFrame object to create a new column from an existing one, and we will need to drop the existing column. Below example creates a “fname” column from “name.firstname” and drops the “name” column.

    df4 = df.withColumn("fname", col("name.firstname"))\
        .withColumn("mname", col("name.middlename"))\
        .withColumn("lname", col("name.lastname"))\
        .drop("name")
    df4.printSchema()
    

    Output:

    root
     |-- dob: string (nullable = true)
     |-- gender: string (nullable = true)
     |-- salary: integer (nullable = true)
     |-- fname: string (nullable = true)
     |-- mname: string (nullable = true)
     |-- lname: string (nullable = true)
    

    6. Using col() Function to Dynamically Rename All or Multiple Columns

    Another way to change all column names on a DataFrame is to use the col() function; you can also use map() to rename multiple columns.

    old_columns = ["dob", "gender", "salary", "fname", "mname", "lname"]
    new_columns = ["DateOfBirth", "Sex", "salary", "firstName", "middleName", "lastName"]
    
    df5 = df4.select([col(old).alias(new) for old, new in zip(old_columns, new_columns)])
    df5.printSchema()
    

    Output:

    root
     |-- DateOfBirth: string (nullable = true)
     |-- Sex: string (nullable = true)
     |-- salary: integer (nullable = true)
     |-- firstName: string (nullable = true)
     |-- middleName: string (nullable = true)
     |-- lastName: string (nullable = true)
    

    7. Using toDF() – To Change All Columns in a PySpark DataFrame

    When we have data in a flat structure (without nested), use toDF() with a new schema to change all column names.

    newColumns = ["newCol1", "newCol2", "newCol3"]
    df = df.toDF(*newColumns)
    df.printSchema()
    

    Output:

    root
     |-- newCol1: string (nullable = true)
     |-- newCol2: string (nullable = true)
     |-- newCol3: string (nullable = true)
    

    Introduction to PySpark for Data Engineering — DataFrame Narrow Transformation

    Introduction to PySpark

    Setup PySpark Environment

    SparkSession & SparkContext

    Resilient Distributed Datasets (RDDs)

    Apache Spark Concepts

    Cache, Persistence and Shared Variables

    DataFrame Introduction

    DataFrame Narrow Transformation

    DataFrame Wider Transformation

    DataFrame Actions

    PySpark SQL Functions

    Advanced DataFrame Features

    PySpark SQL

    Spark Read & Write CSV Files

    Working with JSON Files

    Working with Parquet Files

    What Next?

    Tutorial Not Found