Let us how to add names to DataFrame columns in Pandas.
Creating the DataFrame :
# importing the pandas libraryimport pandas as pd # creating listsl1 =["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 DataFrameteam = pd.DataFrame(list(zip(l1, l2, l3, l4))) # displaying the DataFrameprint(team) |
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.
# adding column name to the respective columnsteam.columns =['Name', 'Code', 'Age', 'Weight'] # displaying the DataFrameprint(team) |
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.
# reanming the DataFrame columnsteam.rename(columns = {'Code':'Code-Name', 'Weight':'Weight in kgs'}, inplace = True) # displaying the DataFrameprint(team) |
Output :
We can see the names of the columns have been changed.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.






