The Wayback Machine - https://web.archive.org/web/20240909181343/https://www.geeksforgeeks.org/how-to-rename-a-pyspark-dataframe-column-by-index/
Open In App

How to rename a PySpark dataframe column by index?

Last Updated : 28 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to know how to rename a PySpark Dataframe column by index using Python. we can rename columns by index using Dataframe.withColumnRenamed() and Dataframe.columns[] methods.  with the help of Dataframe.columns[] we get the name of the column on the particular index and then we replace this name with another name using the withColumnRenamed() method.

Example 1: The following program is to rename a column by its index.   

Python3




# importing required module
import pyspark
from pyspark.sql import SparkSession
  
# creating sparksession and giving
spark = SparkSession.builder.appName('sparkdf').getOrCreate()
  
# demo data of college students
data = [["Mukul", 23, "BBA"],
        ["Robin", 21, "BCA"],
        ["Rohit", 24, "MBA"],
        ["Suraj", 25, "MBA"],
        ["Krish", 22, "BCA"]]
  
# giving column names of dataframe
columns = ["Name", "Age", "Course"]
  
# creating a dataframe
dataframe = spark.createDataFrame(data, columns)
  
# Rename dataframe
df = dataframe.withColumnRenamed(dataframe.columns[0],
                                 "Student Name")
  
# Original dataframe
print("Original Dataframe")
dataframe.show()
  
# Dataframe after rename column
print("Dataframe after rename 0 index column")
df.show()


Output:

Example 2: The following program is to rename multiple columns by these indexes.

Python3




# importing module
import pyspark
  
# importing sparksession from
# pyspark.sql module
from pyspark.sql import SparkSession
  
# creating sparksession and giving
# an app name
spark = SparkSession.builder.appName('sparkdf').getOrCreate()
  
# list  of students  data
data = [[123, "Sagar",   "Rajveer", 22, "BBA"],
        [124, "Rajeev",  "Mukesh",  23, "BBA"],
        [125, "Harish",  "Parveen", 25, "BBA"],
        [126, "Gagan",   "Rohit",   24, "BBA"],
        [127, "Rakesh",  "Mayank",  25, "BBA"],
        [128, "Gnanesh", "Dleep",   26, "BBA"]]
  
# specify column names
columns = ['ID', 'Name', 'Father Name',
           'Age', "Course", ]
  
# creating a dataframe from the lists of data
dataframe = spark.createDataFrame(data, columns)
  
# display original dataframe
print('Actual data in dataframe')
dataframe.show()
  
# Rename column
df = dataframe.withColumnRenamed(dataframe.columns[1], 
                                 "Student Name").withColumnRenamed(
    dataframe.columns[3], "Student Age")
  
# display dataframe after rename column
print('After rename 1 and 3 index column')
df.show()


Output:



Similar Reads

How to rename multiple columns in PySpark dataframe ?
In this article, we are going to see how to rename multiple columns in PySpark Dataframe. Before starting let's create a dataframe using pyspark: C/C++ Code # importing module import pyspark from pyspark.sql.functions import col # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving
2 min read
How to Rename Multiple PySpark DataFrame Columns
In this article, we will discuss how to rename the multiple columns in PySpark Dataframe. For this we will use withColumnRenamed() and toDF() functions. Creating Dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and
2 min read
Rename Duplicated Columns after Join in Pyspark dataframe
In this article, we are going to learn how to rename duplicate columns after join in Pyspark data frame in Python. A distributed collection of data grouped into named columns is known as a Pyspark data frame. While handling a lot of data, we observe that not all data is coming from one data frame, thus there is a need to merge two or more data fram
4 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
How to rename multiple column headers in a Pandas DataFrame?
Here we are going to rename multiple column headers using the rename() method. The rename method is used to rename a single column as well as rename multiple columns at a time. And pass columns that contain the new values and in place = true as an argument. We pass inplace = true because we just modify the working data frame if we pass inplace = fa
5 min read
Rename column by index in Pandas
A column of a data frame can be changed using the position it is in known as its index. Just by the use of the index, a column can be renamed. Dealing with large and complex datasets in Pandas often requires manipulating column names for better analysis. Renaming columns by their index position can be an efficient and straightforward way to achieve
6 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
Get column index from column name of a given Pandas DataFrame
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together. Syntax: DataFrame.columns Return: column names index Syntax: Index.get_loc(key, method=None, tolerance=None) Return: loc : int if unique index, slice if monotonic index, els
2 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Change Column Type in PySpark Dataframe ?
In this article, we are going to see how to change the column type of pyspark dataframe. Creating dataframe for demonstration: Python Code # Create a spark session from pyspark.sql import SparkSession spark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframe columns = ["Name", "Course_Name",
4 min read
Split single column into multiple columns in PySpark DataFrame
pyspark.sql.functions provide a function split() which is used to split DataFrame string Column into multiple columns. Syntax: pyspark.sql.functions.split(str, pattern, limit=- 1) Parameters: str: str is a Column or str to split.pattern: It is a str parameter, a string that represents a regular expression. This should be a Java regular expression.l
4 min read
How to verify Pyspark dataframe column type ?
While working with a big Dataframe, Dataframe consists of any number of columns that are having different datatypes. For pre-processing the data to apply operations on it, we have to know the dimensions of the Dataframe and datatypes of the columns which are present in the Dataframe. In this article, we are going to know how to verify the column ty
4 min read
How to get name of dataframe column in PySpark ?
In this article, we will discuss how to get the name of the Dataframe column in PySpark. To get the name of the columns present in the Dataframe we are using the columns function through this function we will get the list of all the column names present in the Dataframe. Syntax: df.columns We can also get the names of the columns from the list of S
3 min read
How to show full column content in a PySpark Dataframe ?
Sometimes in Dataframe, when column data containing the long content or large sentence, then PySpark SQL shows the dataframe in compressed form means the first few words of the sentence are shown and others are followed by dots that refers that some more data is available. From the above sample Dataframe, we can easily see that the content of the N
5 min read
Removing duplicate rows based on specific column in PySpark DataFrame
In this article, we are going to drop the duplicate rows based on a specific column from dataframe using pyspark in Python. Duplicate data means the same data based on some condition (column values). For this, we are using dropDuplicates() method: Syntax: dataframe.dropDuplicates(['column 1','column 2','column n']).show() where, dataframe is the in
1 min read
Select specific column of PySpark dataframe with its position
In this article, we will discuss how to select a specific column by using its position from a pyspark dataframe in Python. For this, we will use dataframe.columns() method inside dataframe.select() method. Syntax: dataframe.select(dataframe.columns[column_number]).show() where, dataframe is the dataframe namedataframe.columns[]: is the method which
2 min read
Show distinct column values in PySpark dataframe
In this article, we are going to display the distinct column values from dataframe using pyspark in Python. For this, we are using distinct() and dropDuplicates() functions along with select() function. Let's create a sample dataframe. C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql imp
2 min read
How to drop multiple column names given in a list from PySpark DataFrame ?
In this article, we are going to drop multiple columns given in the list in Pyspark dataframe in Python. For this, we will use the drop() function. This function is used to remove the value from dataframe. Syntax: dataframe.drop(*['column 1','column 2','column n']) Where, dataframe is the input dataframecolumn names are the columns passed through a
2 min read
How to change dataframe column names in PySpark ?
In this article, we are going to see how to change the column names in the pyspark data frame. Let's create a Dataframe for demonstration: C/C++ Code # Importing necessary libraries from pyspark.sql import SparkSession # Create a spark session spark = SparkSession.builder.appName('pyspark - example join').getOrCreate() # Create data in dataframe da
3 min read
How to Get substring from a column in PySpark Dataframe ?
In this article, we are going to see how to get the substring from the PySpark Dataframe column and how to create the new column and put the substring in that newly created column. We can get the substring of the column using substring() and substr() function. Syntax: substring(str,pos,len) df.col_name.substr(start, length) Parameter: str - It can
3 min read
How to find the sum of Particular Column in PySpark Dataframe
In this article, we are going to find the sum of PySpark dataframe column in Python. We are going to find the sum in a column using agg() function. Let's create a sample dataframe. C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an
3 min read
Find Minimum, Maximum, and Average Value of PySpark Dataframe column
In this article, we are going to find the Maximum, Minimum, and Average of particular column in PySpark dataframe. For this, we will use agg() function. This function Compute aggregates and returns the result as DataFrame. Syntax: dataframe.agg({'column_name': 'avg/'max/min}) Where, dataframe is the input dataframecolumn_name is the column in the d
2 min read
Add new column with default value in PySpark dataframe
In this article, we are going to see how to add a new column with a default value in PySpark Dataframe. The three ways to add a column to PandPySpark as DataFrame with Default Value. Using pyspark.sql.DataFrame.withColumn(colName, col)Using pyspark.sql.DataFrame.select(*cols)Using pyspark.sql.SparkSession.sql(sqlQuery)Method 1: Using pyspark.sql.Da
3 min read
Add a column with the literal value in PySpark DataFrame
In this article, we are going to see how to add a column with the literal value in PySpark Dataframe. Creating dataframe for demonstration: C/C++ Code # import SparkSession from the pyspark from pyspark.sql import SparkSession # build and create the # SparkSession with name "lit_value" spark = SparkSession.builder.appName("lit_value
3 min read
Filtering rows based on column values in PySpark dataframe
In this article, we are going to filter the rows based on column values in PySpark dataframe. Creating Dataframe for demonstration: C/C++ Code # importing module import spark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('spar
2 min read
Converting a PySpark DataFrame Column to a Python List
In this article, we will discuss how to convert Pyspark dataframe column to a Python list. Creating dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('spark
5 min read
How to add a constant column in a PySpark DataFrame?
In this article, we are going to see how to add a constant column in a PySpark Dataframe. It can be done in these ways: Using Lit()Using Sql query. Creating Dataframe for demonstration: C/C++ Code # Create a spark session from pyspark.sql import SparkSession from pyspark.sql.functions import lit spark = SparkSession.builder.appName('SparkExamples')
2 min read
PySpark dataframe add column based on other columns
In this article, we are going to see how to add columns based on another column to the Pyspark Dataframe. Creating Dataframe for demonstration: Here we are going to create a dataframe from a list of the given dataset. C/C++ Code # Create a spark session from pyspark.sql import SparkSession spark = SparkSession.builder.appName('SparkExamples').getOr
2 min read
Pyspark dataframe: Summing column while grouping over another
In this article, we will discuss how to sum a column while grouping another in Pyspark dataframe using Python. Let's create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSe
4 min read