Rename the column of dataframe in pandas python

In this tutorial we will learn how to rename the column of dataframe in pandas. We will learn

  • how to rename all the column of the dataframe at once
  • how to rename the specific column of our choice by column name.
  • how to rename the specific column of our choice by column index.

 

Let’s try with an example:

Create a dataframe:


import pandas as pd
import numpy as np

# data frame 1
d1 = {'Customer_id':pd.Series([1,2,3,4,5,6]),
'Product':pd.Series(['Oven','Oven','Oven','Television','Television','Television']),
      'State':pd.Series(['California','Texas','Georgia','Florida','Albama','virginia'])}
df1 = pd.DataFrame(d1)
print df1	

so the resultant dataframe will be

Rename the column of dataframe in pandas python 1

 

Rename all the column names in python:

Below code will rename all the column names in sequential order

# rename all the columns in python
df1.columns = ['Customer_unique_id', 'Product_type', 'Province']	
  • first column is renamed as ‘Customer_unique_id’.
  • second column is renamed as ‘Product_type’.
  • third column is renamed as ‘Province’.

so the resultant dataframe will be

Rename the column of dataframe in pandas python 2

 

Rename the specific column in python:

Below code will rename the specific column.


# rename province to state
df1.rename(columns={'Province': 'State'}, inplace=True)

the column named Province is renamed to State with the help of rename() Function so the resultant dataframe will be

Rename the column of dataframe in pandas python 3

 

Rename the specific column value by index in python:

Below code will rename the specific column.

# rename the first column
df1.columns.values[0] = "customer_id"

the first column is renamed to customer_id so the resultant dataframe will be

Rename the column of dataframe in pandas python 4

 

previous Rename the column of dataframe in pandas python                                                                                                         next Rename the column of dataframe in pandas python

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.