Open In App

Add column names to dataframe in Pandas

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we are going to see how to add column names to a dataframe. Let us how to add names to DataFrame columns in Pandas.

Add Column Names to Pandas Dataframe

Below are the steps and methods by which we can add column names in the Pandas dataframe in Python:

Creating the DataFrame

Let’s first create an example DataFrame for demonstration reasons before moving on to adding column names. There are several ways in Pandas to add column names to your DataFrame:

python3




# importing the pandas library
import pandas as pd
 
# creating lists
l1 =["Amar", "Barsha", "Carlos", "Tanmay", "Misbah"]
l2 =["Alpha", "Bravo", "Charlie", "Tango", "Mike"]
l3 =[23, 25, 22, 27, 29]
l4 =[69, 54, 73, 70, 74]
 
# creating the DataFrame
team = pd.DataFrame(list(zip(l1, l2, l3, l4)))
 
# displaying the DataFrame
print(team)


Output

0        1   2   3
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

Here we can see that the columns in the DataFrame are unnamed.

Adding column name to the DataFrame

We can add columns to an existing DataFrame using its columns attribute.

python3




# adding column name to the respective columns
team.columns =['Name', 'Code', 'Age', 'Weight']
 
# displaying the DataFrame
print(team)


 Output

 Name     Code  Age  Weight
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

Now the DataFrame has column names.

Adding Column Name using dataframe()

We can add column name by using giving a parameter inside the dataframe() function.

Python3




column_name = ['Name', 'Code', 'Age', 'Weight']
team = pd.DataFrame(list(zip(l1, l2, l3, l4)), columns=column_name)
print(team)


Output

 Name     Code  Age  Weight 
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

Renaming Column Name of a DataFrame

We can rename the columns of a DataFrame by using the rename() function.

python3




# reanming the DataFrame columns
team.rename(columns = {'Code':'Code-Name',
                       'Weight':'Weight in kgs'},
            inplace = True)
 
# displaying the DataFrame
print(team)


Output

Name Code-Name  Age  Weight in kgs
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

We can see the names of the columns have been changed.



Last Updated : 24 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads