Добавление нового столбца в существующий DataFrame в Pandas
Давайте обсудим, как добавить новые столбцы в существующий DataFrame в Pandas. Есть несколько способов выполнить эту задачу.
Метод №1: объявив новый список как столбец.
# Import pandas package import pandas as pd # Define a dictionary containing Students data data = { 'Name' : [ 'Jai' , 'Princi' , 'Gaurav' , 'Anuj' ], 'Height' : [ 5.1 , 6.2 , 5.1 , 5.2 ], 'Qualification' : [ 'Msc' , 'MA' , 'Msc' , 'Msc' ]} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Declare a list that is to be converted into a column address = [ 'Delhi' , 'Bangalore' , 'Chennai' , 'Patna' ] # Using 'Address' as the column name # and equating it to the list df[ 'Address' ] = address # Observe the result df |
Выход:
Обратите внимание, что длина вашего списка должна соответствовать длине столбца индекса, иначе будет отображаться ошибка.
Метод № 2: Используя DataFrame.insert ()
Это дает возможность добавлять столбец в любом месте, которое нам нравится, а не только в конце. Он также предоставляет различные варианты для вставки значений столбца.
# Import pandas package import pandas as pd # Define a dictionary containing Students data data = { 'Name' : [ 'Jai' , 'Princi' , 'Gaurav' , 'Anuj' ], 'Height' : [ 5.1 , 6.2 , 5.1 , 5.2 ], 'Qualification' : [ 'Msc' , 'MA' , 'Msc' , 'Msc' ]} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Using DataFrame.insert() to add a column df.insert( 2 , "Age" , [ 21 , 23 , 24 , 21 ], True ) # Observe the result df |
Выход:
Метод № 3: Использование метода Dataframe.assign ()
Этот метод создаст новый фрейм данных с новым столбцом, добавленным к старому фрейму данных.
# Import pandas package import pandas as pd # Define a dictionary containing Students data data = { 'Name' : [ 'Jai' , 'Princi' , 'Gaurav' , 'Anuj' ], 'Height' : [ 5.1 , 6.2 , 5.1 , 5.2 ], 'Qualification' : [ 'Msc' , 'MA' , 'Msc' , 'Msc' ]} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Using 'Address' as the column name and equating it to the list df2 = df.assign(address = [ 'Delhi' , 'Bangalore' , 'Chennai' , 'Patna' ]) # Observe the result df2 |
Выход:
Метод №4: Использование словаря
Мы можем использовать словарь Python, чтобы добавить новый столбец в pandas DataFrame. Используйте существующий столбец в качестве ключевых значений, и их соответствующие значения будут значениями для нового столбца.
# Import pandas package import pandas as pd # Define a dictionary containing Students data data = { 'Name' : [ 'Jai' , 'Princi' , 'Gaurav' , 'Anuj' ], 'Height' : [ 5.1 , 6.2 , 5.1 , 5.2 ], 'Qualification' : [ 'Msc' , 'MA' , 'Msc' , 'Msc' ]} # Define a dictionary with key values of # an existing column and their respective # value pairs as the # values for our new column. address = { 'Delhi' : 'Jai' , 'Bangalore' : 'Princi' , 'Patna' : 'Gaurav' , 'Chennai' : 'Anuj' } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Provide 'Address' as the column name df[ 'Address' ] = address # Observe the output df |
Выход:
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.