To rename columns of dataframe in pandas, pandas provides several built-in methods that we will use in this article.
Renaming columns is good when the available dataframe does not have meaningful columns names. We are going to use these ways:
dataframe.columns attribute
dataframe.rename() method
Let's get started with examples to understand the process.
Pandas provide an attribute columns that refers to the columns in the current dataframe.
We can use it to rename the columns by assigning a list of new columns names, and it will rename the columns of the specified dataframe. See the Python code below.
# Rename columns in Pandas Dataframe
import pandas as pd
# Create a Dataframe
df = pd.DataFrame(
{
'A':[1,2],
'B': [10,20]
})
# Print Dataframe
print(df)
print("After renaming column names")
# Rename Dataframe columns
df.columns = ['X', 'Y']
print(df)
Output:
A B
0 1 10
1 2 20
After renaming column names
X Y
0 1 10
1 2 20
Dataframe rename() method is used to rename the columns. It can be used to rename columns or indexes. We must specify what we want to rename in this method. This method takes several arguments. The inplace is used to specify if you want to return a new dataframe after renaming or update the existing. If its true then it will return the same dataframe else returns a new dataframe. See the Python code below.
# Rename columns in Pandas Dataframe
import pandas as pd
# Create a Dataframe
df = pd.DataFrame(
{
'A':[1,2],
'B': [10,20]
})
# Print Dataframe
print(df)
print("After renaming column names")
# Rename Dataframe columns
df.rename(columns = {'A' : 'Y', 'B' : 'Z'}, inplace=True)
print(df)
Output:
A B
0 1 10
1 2 20
After renaming column names
X Y
0 1 10
1 2 20
While renaming the columns, never pass axis = index as it will lead to conflict and the compiler will raise a TypeError: Cannot specify both 'axis' and any of 'index' or 'columns'.
# Rename Dataframe columns
df.rename(columns = {0 : 'Y', 1 : 'Z'}, axis='index', inplace=True)
Output:
in validate_axis_style_args
raise TypeError(msg)
TypeError: Cannot specify both 'axis' and any of 'index' or 'columns'.
We can use this method to rename the index of a dataframe as well. Just pass a dictionary of new index values and specify axis=index. It will rename the index values of the dataframe. See the Python code below.
# Rename index in Pandas Dataframe
import pandas as pd
# Create a Dataframe
df = pd.DataFrame(
{
'A':[1,2],
'B': [10,20]
})
# Print Dataframe
print(df)
print("After renaming index names")
# Rename Dataframe columns
df.rename({0 : 'Y', 1 : 'Z'}, axis='index', inplace=True)
print(df)
Output:
A B
0 1 10
1 2 20
After renaming index names
A B
Y 1 10
Z 2 20