How to Rename Column by Index Using Pandas

Pulamolu Sai Mohan Feb 02, 2024
  1. Use the rename() Function in Pandas
  2. Use the DataFrame.column.values in Pandas
How to Rename Column by Index Using Pandas

DataFrame is a 2D labeled data structure; It is a size-mutable and heterogeneous data structure. The DataFrame contains labeled axes called rows and columns.

This tutorial will tackle different methods to rename columns of a DataFrame by index using Pandas.

Use the rename() Function in Pandas

The Pandas library provides a rename() function that is used to rename the columns of a DataFrame. The rename() function takes a mapper parameter.

A mapper is a dictionary-like data structure that contains the renaming column as key and name as the value that returns a DataFrame; in-place modification can be done by setting inplace = True.

Syntax:

pandas.rename(mapper)

In this tutorial’s example, let’s use the rename() method. First, follow the steps below.

  1. Import the pandas library.
  2. Pass the Mapper to the rename() method.
  3. The rename() method will return a data frame with that column renamed.
  4. Print the DataFrame.

The following code is the implementation of the above approach.

Code:

# importing pandas library
import pandas as pd

# creating a dataframe
df = pd.DataFrame(
    {
        "course": ["C", "Python", "Java"],
        "instructor": ["alex", "alice", "john"],
        "cost": [1000, 2000, 3000],
    }
)

# Dataframe before renaming
print("\n Before Renaming")
print(df)

# renaming the column by index
df = df.rename(columns={df.columns[2]: "price"})

# Dataframe after renaming
print("\n After Renaming")
print(df)

Output:

Before Renaming:

course Mentor cost
C alex 1000
Python alice 2000
Java john 3000

After Renaming:

course Mentor price
C alex 1000
Python alice 2000
Java john 3000

Use the DataFrame.column.values in Pandas

The DataFrame.column.values will return all the column names, and we can use the index to modify the column names. The column.values will return an array of an index.

The following approach is the implementation of the code in this next example.

  1. Import the pandas library.
  2. Retrieve the array of column names using DataFrame.column.values.
  3. Change the name of the column by passing the index.
  4. Print the DataFrame.

Code:

# importing pandas library
import pandas as pd

# creating a dataframe
df = pd.DataFrame(
    {
        "course": ["C", "Python", "Java"],
        "instructor": ["alex", "alice", "john"],
        "cost": [1000, 2000, 3000],
    }
)

# Dataframe before renaming
print("\n Before Renaming")
print(df)

# renaming the column by index
df.columns.values[2] = "price"

# Dataframe after renaming
print("\n After Renaming")
print(df)

Output:

Before Renaming:

course Mentor cost
C alex 1000
Python alice 2000
Java john 3000

After Renaming:

course Mentor price
C alex 1000
Python alice 2000
Java john 3000

Related Article - Pandas DataFrame