Contents
Rename Columns Pandas DataFrame
You can rename a single column or multiple columns of a pandas DataFrame using pandas.DataFrame.rename() method.
In the following set of examples, we will learn how to rename a single column, and how to rename multiple columns of Pandas DataFrame.
Examples
1. Rename single column
To rename a single column, you can use DataFrame.rename() function as shown below.
Python Program
import pandas as pd
# Initialize a DataFrame
df = pd.DataFrame(
[[41, 72, 67, 91],
[21, 78, 69, 87],
[95, 74, 56, 88],
[54, 54, 76, 78]],
columns=['a', 'b', 'c', 'd'])
# Rename single column
df.rename(columns={'b': 'k'}, inplace=True)
# Print the column names
print(df)
Run Code CopyOutput
a k c d
0 41 72 67 91
1 21 78 69 87
2 95 74 56 88
3 54 54 76 78
The column name b has been renamed to k for the Pandas DataFrame.
2. Rename multiple columns
To rename multiple columns, you can use DataFrame.rename() method with multiple old column names and new column names as key:value pairs as shown below.
Python Program
import pandas as pd
# Initialize a DataFrame
df = pd.DataFrame(
[[41, 72, 67, 91],
[21, 78, 69, 87],
[95, 74, 56, 88],
[54, 54, 76, 78]],
columns=['a', 'b', 'c', 'd'])
# Rename single column
df.rename(columns={'b': 'k', 'c': 'm'}, inplace=True)
# Print the column names
print(df)
Run Code CopyOutput
a k m d
0 41 72 67 91
1 21 78 69 87
2 95 74 56 88
3 54 54 76 78
The column named b has been renamed to k and column c has been renamed to m.
Summary
In this Pandas Tutorial, we renamed one or more columns in-place, using pandas.DataFrame.rename() method, with the help of well detailed Python example programs.