Rename a Single Column in Pandas DataFrame

Rename Single Column In Pandas Dataframe

In this article, you will learn how to rename a single column in pandas DataFrame.

Also read: Working with DataFrame Rows and Columns in Python

Using the rename() function

 To rename a column we use rename() method of pandas DataFrame:

Parameters of the rename() function

The rename() function supports the following parameters:

  • Mapper: Function dictionary to change the column names.
  • Index: Either a dictionary or a function to change the index names.
  • Columns: A dictionary or a function to rename columns.
  • Axis: Defines the target axis and is used with mapper.
  • Inplace: Changes the source DataFrame.
  • Errors: Raises KeyError if any wrong parameter is found.

Important points about rename() function:

  1. Can even rename multiple columns, along with single column.
  2. Used to clearly specify the intent.

How to Rename a Single Column?

Let’s quickly create a simple dataframe that has a few names in it and two columns. You can copy this demo code snippet or use the dataframe that you’re working on to rename the single column.

Import pandas as pd
d = {‘Name’ : [‘Raj’, ‘Neha’, ‘Virat’, ‘Deepika’], ‘Profession’ : [‘Artist’, ‘Singer’, ‘Cricketer’, ‘Actress’]}

df = pd.DataFrame(d)

print(df)

#Output: 
          Name          Profession
  0      Raj               Artist 
  1      Neha           Singer
  2      Virat            Cricketer
  3      Deepika       Actress


Now, let’s use our rename() function to change the name of a single column without editing the data within it.

# rename single columns
df1 = df.rename(columns={‘Name’ : ‘PersonName’})
print(df1)

#output: 
          PersonName        Profession
  0      Raj                        Artist 
  1      Neha                     Singer
  2      Virat                      Cricketer
  3      Deepika                Actress

Similarly, we can change the name of the other remaining column:

df2 = df1.rename(columns={‘Profession’ : ‘Prof’})
print(df2)

#output: 
          PersonName         Prof
  0      Raj                         Artist 
  1      Neha                     Singer
  2      Virat                      Cricketer
  3      Deepika                 Actress

Conclusion

We hope that you found the explanation and example helpful and that you can use them in your own projects easily.