How to Rename a Column in Pandas

Published on Aug. 22, 2023, 12:02 p.m.

There are multiple ways to rename a column in Pandas. Here are three common methods:

  1. Using the rename() method:
df.rename(columns={'old_name':'new_name'}, inplace=True)
  1. Assigning a new list of column names to df.columns:
df.columns = ['new_name1', 'new_name2', 'new_name3', ...]

Note that in each of these methods, the inplace=True parameter is used to modify the original DataFrame. If inplace is not used, a new DataFrame with the modified columns will be returned. Additionally, if you want to rename multiple columns at once, you can pass in a dictionary to the rename() method with the old and new column names as key-value pairs.

Here’s an example of how to use the rename() method to rename a single column in Pandas:

import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'old_name': [1, 2, 3], 'other_column': ['a', 'b', 'c']})

# rename the 'old_name' column to 'new_name'
df.rename(columns={'old_name': 'new_name'}, inplace=True)

# print the modified DataFrame
print(df)

This will output:

   new_name other_column
0         1            a
1         2            b
2         3            c

Tags: