Rename Field in spark Dataframe
You can use the withColumnRenamed method to rename a field in a Spark DataFrame. For example, if you have a DataFrame called df and you want to rename the field “oldFieldName” to “newFieldName”, you can use the following code structure:
df.withColumnRenamed("oldFieldName", "newFieldName")
Create the spark DataFrame.
Python3
from pyspark.sql import SparkSession # Create a SparkSession spark = SparkSession.builder.appName ( "CreateDF" ).getOrCreate() data = [( 1 , "John" , "a" , 25 ), ( 2 , "Mike" , "b" , 30 ), ( 3 , "Sara" , "c" , 35 )] # Create a DataFrame df = spark.createDataFrame(data, [ "id" , "fname" , "lname" , "age" ]) df.printSchema() |
Output:
root |-- id: long (nullable = true) |-- fname: string (nullable = true) |-- lname: string (nullable = true) |-- age: long (nullable = true)
Change the name of the single column by providing the oldfieldName and the NewFieldName.
Python3
df1 = df.withColumnRenamed( "fname" , "FirstName" ) df1.printSchema() |
Output:
root |-- id: long (nullable = true) |-- FirstName: string (nullable = true) |-- lname: string (nullable = true) |-- age: long (nullable = true)
Rename multiple columns then we will write the chain of the withColumnRenamed function
Python3
df2 = (df.withColumnRenamed( "fname" , "FirstName" ) .withColumnRenamed( "lname" , "LastName" ) ) df2.printSchema() |
Output:
root |-- id: long (nullable = true) |-- FirstName: string (nullable = true) |-- LastName: string (nullable = true) |-- age: long (nullable = true)
Rename Nested Field in Spark Dataframe in Python
In this article, we will discuss different methods to rename the columns in the DataFrame like withColumnRenamed or select. In Apache Spark, you can rename a nested field (or column) in a DataFrame using the withColumnRenamed method. This method allows you to specify the new name of a column and returns a new DataFrame with the renamed column.
Required Package
PySpark is the Python library for Spark programming. It allows developers to interact with the Spark cluster using the Python programming language. PySpark is a powerful tool for large-scale data processing and analysis, as it allows you to perform distributed computations on large datasets using the power of the Spark engine. you can install Pyspark using the following command:
!pip install pyspark
Contact Us