Python – Pandas Dataframe.rename()


It's quite simple to rename a DataFrame column name in Pandas. All that you need to do is to use the rename() method and pass the column name that you want to change and the new column name. Let's take an example and see how it's done.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
  • Print the input DataFrame, df.
  • Use rename() method to rename the column name. Here, we will rename the column "x" with its new name "new_x".
  • Print the DataFrame with the renamed column.

Example

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)

print "Input DataFrame is:\n", df
df = df.rename(columns={"x": "new_x"})
print "After renaming, the DataFrame is:\n", df

Output

Input DataFrame is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1

After renaming, the DataFrame is:
   new_x  y  z
0      5  4  9
1      2  7  3
2      7  5  5
3      0  1  1

Updated on: 14-Sep-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements