TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: 4 Different Ways to Rename Columns in Pandas
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
PandasPython AdvancedPython Tutorials

4 Different Ways to Rename Columns in Pandas

Last updated: May 26, 2024 5:43 pm
By Harsh S.
Share
7 Min Read
Rename Columns in Pandas Examples
SHARE

Searching for ways to rename a column using Pandas? This is a common operation you might have to perform while using a data frame. This tutorial will walk you through several methods to rename one or more columns in Pandas, providing examples and a comparison of each method to help you choose the most suitable approach for your data manipulation needs.

Contents
Rename a Single Column in PandasRename More than One Column Using PandasRenaming Columns with a DictionaryIn-place vs. Non-Inplace RenamingComparing the Different ApproachesConclusion

How to Rename One or More Columns in Pandas

In this Python tutorial, we’ll cover the following topics. Please make sure you first go through the brief description in the examples and then check out the code. It will ensure you understand the code and its purpose clearly.

By the way, once you finish with this tutorial, you might like to check up on the 3 ways to read a CSV file in Python using Pandas including multiple examples.

Rename a Single Column in Pandas

You can rename a single column in a Pandas DataFrame using the rename() API. Let’s suppose we have a data frame with a column named “old_col,” and we want to rename it to “new_col.”

import pandas as pd

# Create a sample DataFrame
data = {'old_col': [1, 2, 3, 4, 5]}
df = pd.DataFrame(data)

# Rename the 'old_col' to 'new_col'
df.rename(columns={'old_col': 'new_col'}, inplace=True)

print(df)

This code will rename the ‘old_col’ to ‘new_col’ in the data frame. The inplace=True parameter modifies the original data frame. If you omit it or set it to False, the original data frame will remain unchanged.

Rename More than One Column Using Pandas

To rename more than one column in a Pandas DataFrame, pass a dictionary using the current column names as keys and the new names as values. Here’s an example:

# Create a sample DataFrame with more than one column
data = {'old_col1': [1, 2, 3, 4, 5],
        'old_col2': ['A', 'B', 'C', 'D', 'E']}
df = pd.DataFrame(data)

# Rename one or more columns
df.rename(columns={'old_col1': 'new_col1', 'old_col2': 'new_col2'}, inplace=True)

print(df)

This code will rename both ‘old_col1’ and ‘old_col2’ to ‘new_col1’ and ‘new_col2,’ respectively. Again, you can choose to modify the original data frame in place by setting inplace=True.

Renaming Columns with a Dictionary

You can also use a dictionary to rename columns in a more dynamic way. This is useful when you want to rename specific columns based on a mapping. Here’s an example:

# Create a sample DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': ['apple', 'banana', 'cherry', 'date', 'elderberry']}
df = pd.DataFrame(data)

# Define a dict to map old names to new names
column_mapping = {'A': 'Number', 'B': 'Fruit'}

# Rename columns using the dictionary
df.rename(columns=column_mapping, inplace=True)

print(df)

Must Read: Convert Python Dictionary to DataFrame

In this example, we create a dictionary column_mapping that specifies the mapping of old column names to new names. Using this dictionary, we rename the columns in the Pandas data frame accordingly.

In-place vs. Non-Inplace Renaming

As mentioned earlier, you can choose between in-place and non in place renaming by setting the inplace option in the rename API.

  • In place, renaming modifies your original data frame and does not return a new one.
  • The non-inplace renaming returns a new data frame with the renamed columns, leaving the original one unchanged.

Here’s an example to illustrate the difference:

# Create a sample DataFrame
data = {'old_col1': [1, 2, 3, 4, 5],
        'old_col2': ['A', 'B', 'C', 'D', 'E']}
df = pd.DataFrame(data)

# Rename columns non-inplace (returns a new DataFrame)
new_df = df.rename(columns={'old_col1': 'new_col1', 'old_col2': 'new_col2'})

print("Original DataFrame:")
print(df)

print("\nRenamed DataFrame (non-inplace):")
print(new_df)

In this example, df.rename(...) does not modify the original data frame df. It returns a new data frame object, new_df with the renamed columns. This allows you to keep both the original and the renamed versions.

If you want to modify the original data frame in place, you would set the value of the "inplace" option to True as demonstrated in previous examples.

Comparing the Different Approaches

Now, let’s compare the different approaches used to rename one or more columns in Pandas:

MethodUse CaseProsCons
Single Column RenamingRenaming one column– Simple and clean approach
– In-place or non in place option
Not suitable for renaming more than one column
Multi Column RenamingRenaming more than one column– Efficient for renaming several columns
– In-place or non in place option
May become verbose for a large number of columns
Dictionary MappingDynamic renaming based on a Dictionary Mapping– Flexible and dynamic
– Useful for complex renaming patterns
Requires defining a mapping dictionary
Renaming columns in Pandas

Furthermore, a common misconception is that the Pandas set_axis() function also renames columns in a data frame. However, this is not true as it only changes the labels of rows or columns but does not assign new names to columns.

Conclusion

In this tutorial, you’ve learned various examples for renaming columns in a Pandas data frame. Each method has its own benefits and use cases, so the choice depends on your specific requirements:

  • For renaming a single column, use the “Single Column Renaming” method.
  • When renaming more than two or more columns, the “Multi-Column Renaming” method is efficient.
  • If you need dynamic and complex renaming, the “Dictionary Mapping” method is the most suitable.

Remember to consider whether you want to modify the original data frame in place or create a new one with the renamed columns. Your choice should be based on your data manipulation workflow and requirements.

Python for Data Science

Check this Beginners’s Guide to Learn Pandas Series and DataFrames.

19 Min ReadPython Pandas Tutorial

If you want us to continue writing such tutorials, support us by sharing this post on your social media accounts like Facebook / Twitter. This will encourage us and help us reach more people.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article How to Read CSV Files in Python using Pandas How to Read CSV Files in Python using Pandas
Next Article Slice a Python String with Examples How to Slice a Python String with Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x
x