pandas.DataFrame.rename() Method
This method is used to rename the given column name with the new column name or we can say it is used to alter axes labels.
Syntax:
# Standard Syntax
DataFrame.rename(
mapper=None, *,
index=None,
columns=None,
axis=None,
copy=True,
inplace=False,
level=None,
errors='ignore'
)
# Short Syntax or
# Syntax to rename a particular column
DataFrame.rename(
columns = {'old_col_name':'new_col_name'},
inplace = True
)
While using DataFrame.rename(), we need to pass a parameter as a dictionary of old column names and new column names in the form of keys and values. One more parameter (inplace = True) is need to be passed to change the name of a particular column.
Note: If we want to change all the column names in one go, we will use DataFrame.columns directly to assign a list of new column names by using following syntax:
DataFrame.columns = ['new_col_name1', 'new_col_name2', 'new_col_name3', 'new_col_name4']
To work with Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
1) Rename particular columns in Pandas DataFrame
Output:
DataFrame before renamaing column names... Peter Harry Tom John Maths 65 45 67 56 Physics 70 56 87 78 Chemistry 70 66 65 65 English 75 66 53 64 DataFrame after renamaing column names... Peter Mike Jason John Maths 65 45 67 56 Physics 70 56 87 78 Chemistry 70 66 65 65 English 75 66 53 642) Rename all columns in Pandas DataFrame
Output:
DataFrame before renamaing columns... Peter Harry Tom John Maths 65 45 67 56 Physics 70 56 87 78 Chemistry 70 66 65 65 English 75 66 53 64 DataFrame before renamaing columns... Aman Raj Shobha Mohit Maths 65 45 67 56 Physics 70 56 87 78 Chemistry 70 66 65 65 English 75 66 53 64need an explanation for this answer? contact us directly to get an explanation for this answer