Rename Column by index (position) in Pandas

In This Section we will be focusing on how to rename the column by using index in pandas dataframe. There are multiple ways to do it, like renaming nth column, renaming multiple columns by its index or position, Assigning a name to nth column in pandas. lets look at how to rename the column by index or position in pandas with an example for each of these ways.

  • Rename single column by index – Rename nth column in pandas.
  • Assign a name to nth column in pandas
  • Rename multiple columns in pandas by index or position

Let’s Look at these cases with Example,

 

Create Dataframe:

 
## create dataframe 

import pandas as pd 
import numpy as np 
#Create a DataFrame 
import pandas as pd 
import numpy as np 
d = { 'Name':['Alisa','Bobby','Cathrine','Jodha','Raghu','Ram'], 
     'Age':[26,23,23,23,23,24], 
     'Score':[85,31,55,55,31,77],
     'City':['Newyork','Seattle','Toronto','California','Delhi','Mumbai']} 
    
df = pd.DataFrame(d,columns=['Name','Age','Score','City']) 
df


The Resultant dataframe is

Rename-Column-by-index-position-in-Pandas-1

 

 

Assign a column name to nth column in pandas:

df.columns.values[index] will assign the column name to that specified index as shown below.

 

df.columns.values[0] = 'Student_Name'
df

0th column Index is assigned with new name “Student_Name”. so the resultant dataframe will be

Rename-Column-by-index-position-in-Pandas-2

 

 

Rename single column by index – Rename nth column in pandas

df.rename keyword along the column index (column position) and column name to be renamed  is mentioned  which will rename the column name to that specified index as shown below.

 

df.rename(columns={df.columns[2]: 'Course_Score'},inplace=True)

df

2nd  column Index is replaced with new name “Course_Score” so the resultant dataframe will be
Rename-Column-by-index-position-in-Pandas-3

 

 

Rename multiple columns at once by index in pandas

df.rename keyword along with the list the column index (column position) and column name to be renamed  is mentioned  which will rename the multiple columns at once using the column index in pandas  as shown below.

 

# Rename multiple columns by Index

df.rename(columns={df.columns[1]: 'Student_Age', df.columns[3]: 'Student_City'},inplace=True)
df

1st and 3rd column Index is replaced with new name namely “Student_Age” and “Student_City” respectively

Rename-Column-by-index-position-in-Pandas-4

 

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts