Как добавить одну строку в существующий фрейм данных Pandas?
В этой статье мы увидим, как добавить новую строку значений в существующий фрейм данных. Это можно использовать, когда мы хотим вставить новую запись в наши данные, которую мы, возможно, пропустили добавление ранее. Для этого есть разные методы. Теперь посмотрим на примерах, как мы можем это сделать.
Пример 1:
We can add a single row using DataFrame.loc. We can add the row at the last in our dataframe. We can get the number of rows using len(DataFrame.index) for determining the position at which we need to add the new row.
from IPython.display import display, HTML import pandas as pdfrom numpy.random import randint dict = {"Name":["Martha", "Tim", "Rob", "Georgia"], "Maths":[87, 91, 97, 95], "Science":[83, 99, 84, 76] } df = pd.DataFrame(dict) display(df) df.loc[len(df.index)] = ["Amy", 89, 93] display(df) |
Output:

Example 2:
We can also add a new row using the DataFrame.append() function
from IPython.display import display, HTML import pandas as pdimport numpy as np dict = {"Name":["Martha", "Tim", "Rob", "Georgia"], "Maths":[87, 91, 97, 95], "Science":[83, 99, 84, 76] } df = pd.DataFrame(dict) display(df) df2 = {"Name": "Amy", "Maths": 89, "Science": 93}df = df.append(df2, ignore_index = True) display(df) |
Output:

Example 3:
We can also add multiple rows using the pandas.concat() by creating a new dataframe of all the rows that we need to add and then appending this dataframe to the original dataframe.
from IPython.display import display, HTML import pandas as pdimport numpy as np dict = {"Name":["Martha", "Tim", "Rob", "Georgia"], "Maths":[87, 91, 97, 95], "Science":[83, 99, 84, 76] } df1 = pd.DataFrame(dict)display(df1) dict = {"Name":["Amy", "Maddy"], "Maths":[89, 90], "Science":[93, 81] } df2 = pd.DataFrame(dict)display(df2) df3 = pd.concat([df1, df2], ignore_index = True)df3.reset_index() display(df3) |
Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.