How to use rename() function In Python Pandas
Renaming a Single Column Name with an Index Number
Using the df.rename() function, we can change the name of a single column using an index number. The old column names are the keys and the new column names are the values of a dictionary that is sent as an argument to this procedure. The desired new name may be used as the value, and the index position of the column name can be used as the key. Assume, for instance, that we wish to change the name of the second column (index 1) from “Age” to “Years.” The code that follows is usable:
Python3
import pandas as pd df = pd.read_csv( 'data.csv' ) print (df.columns) df = df.rename(columns = {df.columns[ 1 ]: 'Years' }) df |
Output:
Index(['Name', 'Age', 'Gender', 'Grade'], dtype='object')
Name Years Gender Grade
0 Alice 12 F A
1 Bob 13 M B
2 Charlie 14 M C
3 David 12 M A
4 Eve 13 F B
This will modify the DataFrame in place and change the column name from ‘Age’ to ‘Years’. If we print the DataFrame, we will see the updated column name.
Renaming Multiple Column Names with Index Numbers
To rename numerous column names with index numbers, we may use the same df.rename() function, but with a bigger dictionary including more key–value pairs. Consider the following scenario: let’s say we wish to change the labels of the first and third columns (index 0 and 2) from “Name” and “Gender” to “Student” and “Sex,” respectively. The code that follows is usable:
Python3
df = df.rename(columns = {df.columns[ 0 ]: 'Student' , df.columns[ 2 ]: 'Sex' }) print (df) |
Output:
Student Years Sex Grade
0 Alice 12 F A
1 Bob 13 M B
2 Charlie 14 M C
3 David 12 M A
4 Eve 13 F B
This will modify the DataFrame in place and change the column names from ‘Name’ and ‘Gender’ to ‘Student’ and ‘Sex’, respectively. If we print the DataFrame, we will see the updated column names.
Rename column name with an index number of the CSV file in Pandas
In this blog post, we will learn how to rename the column name with an index number of the CSV file in Pandas.