Добавить имена столбцов в фрейм данных в Pandas

Опубликовано: 27 Марта, 2022

Давайте, как добавить имена в столбцы DataFrame в Pandas.

Creating the DataFrame :

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

Выход :

Здесь мы видим, что столбцы в DataFrame не имеют имени.

Adding column name to the DataFrame : We can add columns to an existing DataFrame using its columns attribute.

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


Выход :

Теперь у DataFrame есть имена столбцов.

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

# reanming the DataFrame columns
team.rename(columns = {"Code":"Code-Name"
                       "Weight":"Weight in kgs"}, 
            inplace = True)
  
# displaying the DataFrame
print(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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

Next
Adding new column to existing DataFrame in Pandas
Recommended Articles
Page :
Article Contributed By :
ankurv343
@ankurv343
Vote for difficulty
Current difficulty : Medium
Article Tags :
  • Python pandas-dataFrame
  • Python-pandas
  • Python
Report Issue
Python

РЕКОМЕНДУЕМЫЕ СТАТЬИ