Add column names to dataframe in Pandas

Let us how to add names to DataFrame columns in Pandas.

Creating the DataFrame :

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output :

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


 
Output :

Now the DataFrame has column names.

Renaming column name of a DataFrame : We can rename the columns of a DataFrame by using the rename() function.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.