The Wayback Machine - https://web.archive.org/web/20240722102252/https://www.geeksforgeeks.org/how-to-add-one-row-in-an-existing-pandas-dataframe/
Open In App

How to add one row in an existing Pandas DataFrame?

Last Updated : 25 Jun, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Adding rows to a Pandas DataFrame is a common task in data manipulation. Here are the primary methods to add rows to a DataFrame, along with their syntax and examples in Pandas.

Add Row to Pandas Dataframe

# Append the new row to the DataFrame
df = df.append(new_row, ignore_index=True)
print(df)

Now let’s see with the help of examples how we can do this

Add Row to Dataframe using df.loc

We can add a single row using DataFrame.loc. We can append row to dataframe at the last. We can get the number of rows using len(DataFrame.index) for determining the position at which we need to add the new row.

Python
from IPython.display import display, HTML

import pandas as pd
from 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:

add-row-to-existing-pandas-dataframe

Pandas Add Row to Dataframe using df.append

We can also add a new row using the DataFrame.append() function

Python
from IPython.display import display, HTML

import pandas as pd
import 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)

# This code is modified by Susobhan Akhuli

Output:

add-row-to-existing-pandas-dataframe

Python Pandas Add Row to Dataframe using Concat

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.

Python
from IPython.display import display, HTML

import pandas as pd
import 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)

Output:

add-row-to-existing-pandas-dataframe

How to Add Rows to Pandas Dataframe – FAQs

How to add one row of a DataFrame to another DataFrame?

You can use the append() method in Pandas to add one row from one DataFrame to another DataFrame.

import pandas as pd

# Existing DataFrames
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5], 'B': [6]}) # Single-row DataFrame to add

# Append row from df2 to df1
df_combined = df1.append(df2, ignore_index=True)

print(df_combined)

How to create a single-row DataFrame in Pandas?

You can create a single-row DataFrame by passing a dictionary with column names as keys and values as a list containing single row data.

import pandas as pd

data = {'A': [1], 'B': [2]} # Single-row data
df = pd.DataFrame(data)

print(df)

How to get 1 row as a DataFrame in Pandas?

If you have an existing DataFrame and want to extract a single row as another DataFrame, you can use slicing (‘iloc[]’) or filtering.

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Get the first row as a DataFrame
row_df = df.iloc[[0]]

print(row_df)

What is the append() method in Pandas?

The ‘append()’ method in Pandas is used to concatenate rows from one DataFrame to another. It creates a new DataFrame by combining rows from the original DataFrame and another DataFrame or Series.

What is the difference between concat and append in DataFrame?

concat() and append() are both methods used to concatenate DataFrames in Pandas:

  • concat() can concatenate multiple DataFrames along either axis (rows or columns) and allows for more flexible concatenation options.
  • append() is a specific case of concat() used to append rows from one DataFrame to another DataFrame and is more straightforward for appending rows.
import pandas as pd

# Example DataFrames
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})

# Using append()
appended_df = df1.append(df2, ignore_index=True)

# Using concat()
concatenated_df = pd.concat([df1, df2], ignore_index=True)

print("Appended DataFrame:")
print(appended_df)

print("\nConcatenated DataFrame:")
print(concatenated_df)

Output:

Appended DataFrame:
A B
0 1 3
1 2 4
2 5 7
3 6 8

Concatenated DataFrame:
A B
0 1 3
1 2 4
2 5 7
3 6 8




    Previous Article
    Next Article

    Similar Reads

    How to Fix an "Error When Adding a New Row to My Existing DataFrame in Pandas"
    Pandas is a powerful and widely-used library in Python for data manipulation and analysis. One common task when working with data is adding new rows to an existing DataFrame. However, users often encounter errors during this process. This article will explore common errors that arise when adding new rows to a DataFrame and provide solutions to fix
    6 min read
    Add a row at top in pandas DataFrame
    Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can add a row at top in pandas DataFrame.Observe this dataset first. C/C++ Code # importing pandas module import pandas as pd # making data frame df = pd.read_csv("https://media.geeksforg
    1 min read
    How to add header row to a Pandas Dataframe?
    A header necessarily stores the names or headings for each of the columns. It helps the user to identify the role of the respective column in the data frame. The top row containing column names is called the header row of the data frame. There are two approaches to add header row to a Pandas Dataframe in case the original dataframe doesn't have a h
    4 min read
    Append list of dictionary and series to a existing Pandas DataFrame in Python
    In this article, we will discuss how values from a list of dictionaries or Pandas Series can be appended to an already existing pandas dataframe. For this purpose append() function of pandas, the module is sufficient. Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None) Parameters :other : DataFrame or Series/dict-
    2 min read
    How to insert a pandas DataFrame to an existing PostgreSQL table?
    In this article, we are going to see how to insert a pandas DataFrame to an existing PostgreSQL table. Modules neededpandas: Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fas
    3 min read
    How to Append Pandas DataFrame to Existing CSV File?
    In this discussion, we'll explore the process of appending a Pandas DataFrame to an existing CSV file using Python. Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the 'a' parameter to write the DataFrame to the CSV file in append mode. Pandas DataFrame to_csv() Syntax Syntax : df.t
    3 min read
    Adding new column to existing DataFrame in Pandas
    Adding new columns to an existing DataFrame is a fundamental task in data analysis using Pandas . It allows you to enrich your data with additional information and facilitate further analysis and manipulation. This article will explore various methods for adding new columns, including simple assignment, the insert() method, the assign() method. Let
    7 min read
    Create a new column in Pandas DataFrame based on the existing columns
    While working with data in Pandas, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to create new columns in the DataFrame based on the result of some operations on the existing columns in the DataFrame. Let's discuss several ways in which we can do that. Given a Da
    4 min read
    How to slice a PySpark dataframe in two row-wise dataframe?
    In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
    4 min read
    Change column names and row indexes in Pandas DataFrame
    Given a Pandas DataFrame, let's see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns.Each row is a measurement of some instance while column is a vector which
    4 min read
    Practice Tags :
    three90RightbarBannerImg