Pandas DataFrame- Rename column labels
To change or rename a DataFrame’s column labels in pandas, simply assign a new column label (array) to the dataframe column name.
In this tutorial, we will learn how to rename the column labels of Pandas DataFrame, with the help of well illustrated example programs.
Syntax
The syntax for assigning new column names is given below.
dataframe.columns = new_columns
The new_columns
must be an array of the same length as the number of columns in the dataframe.
Example 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 the dataframe’s column property.
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)
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 Panda Guide we renamed the DataFrame’s column labels, with the help of detailed Python example programs.
Hope this helps!