How to Change Column Labels in Pandas DataFrame? Examples


Pandas DataFrame- Rename Column Labels

To change or rename the column labels of a DataFrame in pandas, just assign the new column labels (array) to the dataframe column names.

https://youtu.be/a2Lnzl2WtCc

In this tutorial, we shall learn how to rename column labels of a Pandas DataFrame, with the help of well illustrated example programs.


Syntax

The syntax to assign new column names is given below.

dataframe.columns = new_columns

The new_columns should be an array of length same as that of number of columns in the dataframe.


Examples

1. Rename column labels of DataFrame

In this example, we will create a dataframe with some initial column names and then change them by assigning columns attribute of the dataframe.

Python Program

import numpy as np
import pandas as pd

df_marks = pd.DataFrame(
	[['Somu', 68, 84, 78, 96],
	['Kiku', 74, 56, 88, 85],
	['Amol', 77, 73, 82, 87],
	['Lini', 78, 69, 87, 92]],
	columns=['name', 'physics', 'chemistry', 'algebra', 'calculus'])

print('Original DataFrame\n------------------------')
print(df_marks)

#rename columns
df_marks.columns = ['name', 'physics', 'biology', 'geometry', 'calculus']
print('\n\nColumns Renamed\n------------------------')
print(df_marks)

Explanation

  1. The program imports the numpy and pandas libraries for data manipulation.
  2. A DataFrame named df_marks is created using the pd.DataFrame() function. It contains a nested list representing rows of data and a list of column names: 'name', 'physics', 'chemistry', 'algebra', and 'calculus'.
  3. The DataFrame is printed using print(), showing the initial structure of the table with original column names.
  4. Column names are updated by assigning a new list of column names ('name', 'physics', 'biology', 'geometry', and 'calculus') to df_marks.columns.
  5. The modified DataFrame is printed again, displaying the updated column names while retaining the original data values.

Output

Original DataFrame
------------------------
   name  physics  chemistry  algebra  calculus
0  Somu       68         84       78        96
1  Kiku       74         56       88        85
2  Amol       77         73       82        87
3  Lini       78         69       87        92


Columns Renamed
------------------------
   name  physics  biology  geometry  calculus
0  Somu       68       84        78        96
1  Kiku       74       56        88        85
2  Amol       77       73        82        87
3  Lini       78       69        87        92

New column labels have been applied to the DataFrame.


Summary

In this Pandas Tutorial, we renamed column labels of DataFrame, with the help of well detailed Python example programs.




Python Libraries