Renaming Columns in Pandas

Renaming Columns in Pandas

3 mins read530 Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Oct 3, 2023 11:46 IST

Renaming Columns in Pandas is one of the basic but most important processes while doing data analysis or cleaning to give a meaningful name so that anyone can easily understand the data. In this article, we will discuss different methods of renaming columns in Pandas with the help of examples.

2022_10_MicrosoftTeams-image-54.jpg

When the raw data is imported into pandas for analysis, sometimes it has messy names, so you need to rename the columns with a meaningful name. Pandas offer different methods to rename the name of columns/indexes, such as rename (), add_prefix (), add_suffix (), set_axis (). This article will briefly discuss different methods of renaming columns in Pandas.

Must Check: Pandas Online Courses and Certifications

Must Check: Pandas Interview Questions for Data Scientists

Table of Content

Before discussing different methods of renaming columns in pandas, let’s set up the data first, i.e., we will create a data frame to perform the actions on it.

Also Read: How to read and write files using Pandas

Create a DataFrame

Input

 
#import Pandas
import pandas as pd
#create a dataframe
faculties = pd.DataFrame({'Name' : ['Ramanujan', 'CV Raman', 'Tagore', 'CNR Rao', 'JC Bose'],
'Department' : ['Mathematics', 'Physics', 'Literature', 'Chemistry', 'Biology'],
'Subject' : ['Integral Calculus', 'Optics', 'Bengali Literature', 'Solid State Chemistry & Catalyst', 'Plants'],
'Number of Class' : [3, 2, 1, 2, 3]})
#print dataframe
print (faculties)
Copy code

Output

We will now use the above data frame (faculties) to better understand renaming columns in pandas. 

Also Read: Series vs. DataFrame in Pandas

Enumerate in Python
Enumerate in Python
Enumerate is a built-in function of python, that helps to count each item of a list, tuple, or any data structure that can be iterated. In this article, we will...read more
Introduction to Iterators in Python
Introduction to Iterators in Python
Have you ever wondered how Python handles looping through collections such as lists or dictionaries? This is where iterators come into play. An iterator in Python is an object that...read more
Working with Python Datetime Module
Working with Python Datetime Module
The Python datetime module supplies classes to manipulate times and dates. It is categorized into date, datetime, time, timedelta, tzinfo and timezone.

Methods of Renaming Columns

rename () function

rename () function in pandas is used when we need to make changes in selected columns since we have to specify the name of the columns that have to be renamed.

Example: Change the column’s name from ‘Name’ to ‘Professor.’

Input

 
# using DataFrame.rename() function
faculties.rename(columns = {'Name': 'Professor'}, inplace = True)
#print the name of new columns
print("Name of New Columns:", faculties.columns)
Copy code
How to use pass statement in Python
How to use pass statement in Python
A pass statement in Python is a null statement that act as a placeholder for future code. In this article, we will briefly discuss how to use pass statement with...read more
Pattern Programs in Python
Pattern Programs in Python
Do you want to learn how to make different patterns in python.Here in this article you will find 20 python programs for different pyramid patterns. This article implemented different Pattern...read more
Memory Management in Python
Memory Management in Python
For any programming language, it is very important how it is managing the memory allocation as it impacts the efficiency of machine. In this article we will discuss how python...read more

set_axis() function

set_axis() function assigns the required index to either a column or index axis.

To rename the column name set:

  • axis = ‘columns’ or
  • axis = 1

Example: Change the column’s name from Name Department, Subject, and Number of class to A, B, C, and D.

Input

 
# using DataFrame.rename() function
faculties.set_axis(['A', 'B', 'C', 'D'], axis='columns', inplace=True)
#print the name of new columns
print("Name of New Columns:", faculties.columns)
Copy code
Abstraction in Python
Abstraction in Python
In this article, we will discuss abstraction in python and how to implement abstraction using abstract classes and methods.
Introduction to Recursion Functions in Python
Introduction to Recursion Functions in Python
When programming, in many places you would have implemented a function that invokes or calls another function. However, when a function calls itself we call that recursion.
Python Sorted() Function
Python Sorted() Function
The sorted() function is designed to return a new sorted list from the items in an iterable. Whether you're dealing with numbers, strings, or custom objects, sorted() can handle it...read more

add_prefix(), add_sufix() function

We can also change the column’s name by adding relevant prefixes (start of the column name) and suffixes (end of the column name).

Example: Add ‘column_name:’ and ‘.’ before the start and end of the given column name, respectively.

Input

 
#using DataFrame.add_prefix and DataFrame.add_suffix
faculties = faculties.add_prefix('column_name: ')
faculties = faculties.add_suffix('.')
#print the name of new columns
print("Name of New Columns:", faculties.columns)
faculties.head()
Copy code

Output

Also Read: Data Cleaning using Pandas.

Ternary Operators in Python
Ternary Operators in Python
For a Python programmer, one of the major concerns is the size and readability of the code. Any efficient program in Python is supposed to be easily readable, short, and...read more
How to Convert Celsius to Fahrenheit in Python
How to Convert Celsius to Fahrenheit in Python
One of the most common Python programs for beginners is to convert temperature from Celsius to Fahrenheit and vice versa. This tutorial will help you learn how to perform both...read more
Rock Paper Scissors Game in Python
Rock Paper Scissors Game in Python
ROCK PAPER SCISSORS is a traditional two-player game. Each round, players begin by saying, “rock, paper, scissors, shoot!” Each player holds their fist for the rock, flat hand for the...read more

dataframe.column() function

  • Rename all columns

We can rename all the columns of any DataFrame by the rename () function and the set_axis() function. But using dataframe.column (), we can directly rename the names of columns.

  • Here, we have to assign a list of name corresponding to the name of the column that we need to change.
  • The only limitation of this method is that it changes the name of all columns, even if we only want to change in fewer columns.

Example: Change the column’s name from Name Department, Subject, and Number of class to col_A, col_B, col_C, and col_D.

Input

 
#using DataFrame.columns()
faculties.columns = ['col_A', 'col_B', 'col_C', 'col_D']
#print the name of new columns
print("Name of New Columns:", faculties.columns)
faculties.head()
Copy code

Output

Also Read: Sorting Data using Pandas.

How to Check if Two Python Strings are Anagrams
How to Check if Two Python Strings are Anagrams
An Anagram is a word or phrase that is formed by rearranging all the letters of a different word or phrase exactly once such as elbow and below. In this...read more
Python Program to Swap Two Variables
Python Program to Swap Two Variables
In this article, we will learn how to swap two variables using the Python programming language. Here’s the agenda!
Dice Roll Generator in Python
Dice Roll Generator in Python
Creating a dice roll generator in Python is a great way to get started with the language. Not only does it give you the opportunity to work with some fundamental...read more
  • Replace specific characters in columns

Till now, we have learned how to rename the columns in pandas using different methods. But how will you do that if we have to remove any specific character or word in the columns’ names?

Let’s make it simple; from the above example, remove (or replace) ‘col’ from the name of each column.

So, to do that, we will use DataFrame.columns.str.replace() function

Input

 
#using DataFrame.columns.str.replace()
faculties.columns = faculties.columns.str.replace('col', '')
#print the name of new columns
print("Name of New Columns:", faculties.columns)
faculties.head()
Copy code
Free QR Code Generator using Python
Free QR Code Generator using Python
Do you want to know QR code is generated? Then read this blog which tell you how to implement this using python
Python Program to Check Leap Year
Python Program to Check Leap Year
Do you want to know how to check leap year using python? Then this article will provide you three methods to find it out.
Find the Second Occurrence of a Substring in Python String
Find the Second Occurrence of a Substring in Python String
In this article, we will discuss different methods (find, split and regular expression module) to find the second occurrence of a substring in a given string.

Conclusion

In this article, we have briefly discussed different methods of renaming columns in pandas with the help of examples.

Hope, you will like the article.

Keep Learning!!

Keep Sharing!!

Handwritten Digit Recognition with 98% Accuracy
Handwritten Digit Recognition with 98% Accuracy
In this Tensorflow tutorial, you will learn how to train a multi layer perceptron on MNIST dataset for Handwritten Digit Recognition. In this Tensorflow tutorial, you will learn how to...read more
Top 110+ Python Interview Questions and Answers
Top 110+ Python Interview Questions and Answers
Python is a widely-used general-purpose, object-oriented, high-level programming language. It is used to create web applications, and develop websites and GUI applications. The popularity of the language is due to...read more
About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio