Udit Vashisht
Author: Udit Vashisht


How to insert a new row in a Pandas Dataframe?

  • 4 minutes read
  • 124 Views
How to insert a new row in a Pandas Dataframe?
var aax_size='728x90'; var aax_pubname = 'saralgyaan0d-21'; var aax_src='302';

    Table of Contents

How to insert a new row to a Pandas Dataframe?

In this post, we will learn to insert/add a new row to an existing Pandas Dataframe using pandas.DataFrame.loc, pandas.concat() and numpy.insert(). Using these methods you can add multiple rows/lists to an existing or an empty Pandas DataFrame.

Creating a Pandas Dataframe from Pandas Series objects.

First of all, we will create a Pandas Dataframe from two Pandas Series objects as under :-

s1 = pd.Series([1, 2, 3])
s2 = pd.Series([4, 5, 6])
cols =  ["A", "B", "C"]

df = pd.DataFrame([list(s1), list(s2)],  columns =  cols)

   A  B  C
0  1  2  3
1  4  5  6

[2 rows x 3 columns]

Now assume that we need to append the following list as a new row to the Pandas Dataframe.

new_row = [7, 8, 9]

Inserting a new row to a Pandas Dataframe using .loc

We can insert a new row as the last row to a Pandas Dataframe using pandas.DataFrame.loc as shown in the following code:-

df.loc[-1] = new_row

   A  B  C
0  1  2  3
1  4  5  6
-1 7  8  9

[3 rows x 3 columns]

But, here the index of the last row is -1, you can reset the index of a Pandas DataFrame using df.reset_index():-

df.reset_index(drop=True)
   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9

[3 rows x 3 columns]

Inserting a new row to a Pandas Dataframe using pandas.concat()

You can also add a new row to a Pandas Dataframe using pandas.concat() by converting the row into a Dataframe and then concatenating it to the existing Dataframe as under:-

new_df = pd.DataFrame([new_row], columns=cols)

   A  B  C
0  7  8  9

[1 row x 3 columns]

df = pd.concat([df, new_df])

   A  B  C
0  1  2  3
1  4  5  6
0  7  8  9

[3 rows x 3 columns]

Here, the new Pandas Dataframe has preserved the index of the row, but you can reset the index while concatenating by using the argument ‘ignore_index = True’ in pandas.concat().

df = pd.concat([df, new_df], ignore_index = True)

   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9

[3 rows x 3 columns]

You can also add the new row to the top of the existing Dataframe by switching the order while using pandas.concat().

df = pd.concat([new_df, df], ignore_index = True)

   A  B  C
0  7  8  9
1  1  2  3
2  4  5  6

[3 rows x 3 columns]

Inserting a new row to a Pandas Dataframe using numpy.insert()

You can also insert a new row to an existing Pandas Dataframe using numpy.insert(). The major advantage of using numpy.insert() to insert a new row to the Pandas Dataframe is that you can insert the new row at an arbitrary or a desired position/index in the dataframe by declaring the desired index of the row in np.insert().

import numpy as np

df = pd.DataFrame(np.insert(df.values, 1, new_row, axis=0)) # 1 is the index at which we need to insert the new row.

   A  B  C
0  1  2  3
1  7  8  9
2  4  5  6

[3 rows x 3 columns]

Inserting a new row at a desired index to a Pandas Dataframe using pandas.concat()

Alternatively, you can also insert a new row at an arbitrary or desired index using pandas.concat() using slicing (df.iloc) as under:-

df = pd.concat

df = pd.concat([df.iloc[:1], new_df, df.iloc[1:]], ignore_index = True)

   A  B  C
0  1  2  3
1  7  8  9
2  4  5  6

[3 rows x 3 columns]

How to add a new row to a Pandas Dataframe? - Video Tutorial


If you have any query regarding this post, feel free to comment below. Also, if you have liked this post, please share it with someone who needs it.



Related Posts

Python Pandas Tutorial - Introduction and Installation
By Udit Vashisht

Python Pandas Tutorial - Introduction

Python Pandas or Python Data Analysis Library is an open-source library which provides high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Python Pandas is also used for timeseries data analysis. Python Pandas is derived from the term ...

Read More
Python Pandas Objects - Pandas Series and Pandas Dataframe
By Udit Vashisht

Python Pandas Objects - Pandas Series and Pandas Dataframe

In the last post, we discussed introduction and installation of Python Pandas. In this post, we will learn about pandas’ data structures/objects. Pandas provide two type of data structures:-

  • Pandas Series
  • Pandas Dataframe

Pandas Series

Pandas ...

Read More
Python Pandas Tutorial - Creating Pandas Dataframe from CSV file and other file formats
By Udit Vashisht

Python Pandas Tutorial - Create Pandas Dataframe from a CSV File - Reading in data from various files

In the last post about python pandas, we learnt about the python pandas data objects - python pandas series and python pandas dataframe and also learned to construct a ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta