How to RENAME multiple Column Headers in a Pandas DataFrame in Python

How to RENAME multiple Column Headers in a Pandas DataFrame in Python

Renaming multiple column headers in a Pandas DataFrame in Python can be done by using the rename() function. This function allows you to change the names of multiple columns at once by passing a dictionary containing the current column names as keys and the new column names as values.

First, you need to import the Pandas library and create a DataFrame. For example, you can create a DataFrame with some sample data.

import pandas as pd

data = {'product': ['Apple', 'Banana', 'Cherry', 'Date', 'Eggplant'],

'price': [1.2, 2.3, 2.5, 1.7, 2.0],

'quantity': [3, 5, 2, 4, 8]}

df = pd.DataFrame(data)

Next, you can use the rename() function to change the names of multiple columns. You can pass a dictionary containing the current column names as keys and the new column names as values to the rename() function.

For example, if you want to change the name of the ‘product’ column to ‘Item’ and the ‘price’ column to ‘Cost’, you can use the following code:

df = df.rename(columns={'product': 'Item', 'price': 'Cost'})

Alternatively, you can also use the rename() function inplace to change the name of column in the same dataframe

df.rename(columns={'product': 'Item', 'price': 'Cost'}, inplace=True)

By using the rename() function in this way, you can easily change the names of multiple columns at once in a Pandas DataFrame in Python. This can be useful for data analysis, as it allows you to better understand the data and make it easier to work with. It can also be useful when working with other people’s data and you want to make the column names more meaningful to you.

 

In this Learn through Codes example, you will learn: How to RENAME multiple Column Headers in a Pandas DataFrame in Python.



Find more … …

Data Wrangling in Python – How to Rename Column Headers In pandas

Excel formula for Beginners – How to Sum matching columns in Excel

Learn Java by Example: Java Program to Rename File

Data Wrangling in Python – How to Rename Multiple pandas Dataframe Column Names

Essential Gigs