In this article we will discuss how to add a single or multiple rows in a dataframe using dataframe.append() or loc & iloc.

Pandas Dataframe provides a function dataframe.append() i.e.

Here, ‘other’ parameter can be a DataFrame , Series or Dictionary or list of these. Also, if ignore_index is True then it will not use indexes.

Let’s see how to use dataframe.append() to add rows in a dataframe.

First create a dataframe using list of tuples i.e.

Contents of the dataframe dfObj are,

Add row in the dataframe using dataframe.append() and Dictionary

In dataframe.append() we can pass a dictionary of key value pairs i.e.

  • key = Column name
  • Value = Value at that column in new row

Let’s add a new row in above dataframe by passing dictionary i.e.

It will not modify the existing dataframe object dfObj, it will return a new dataframe containing copy of contents of existing dataframe and with a new row appended at it’s end. Contents of the dataframe returned are,

New DataFrame’s index is not same as original dataframe because ignore_index is passed as True in append() function. Also, for columns which were not present in the dictionary NaN value is added.

Passing ignore_index=True is necessary while passing dictionary or series otherwise following TypeError error will come i.e.

“TypeError: Can only append a Series if ignore_index=True or if the Series has a name”

Add row in the dataframe using dataframe.append() and Series

We can also pass a series to append() to append a new row in dataframe i.e.

While creating a series object we pass the index names same as index names of dataframe. Contents of the dataframe returned are,

Add multiple rows in the dataframe using dataframe.append() and Series

We can pass a list of series too in dataframe.append() for appending multiple rows in dataframe.

So, let’s create a list of series with same column names as dataframe i.e.

Now pass this list of series to the append() function i.e.

Contents of the dataframe returned are,

Add a row from one dataframe to other dataframe using dataframe.append()

Let’s create an another dataframe i.e.

Contents of this second dataframe objec dfObj2 are,

Now add a row at index ‘b’ from dataframe dfObj2 to dataframe dfObj i.e.

Contents of the dataframe returned are,

Add a row in the dataframe using loc[] & list

It will add a new row in dataframe dfObj with index ‘k’ i.e.

If dataframe already had any row with index name ‘k’ then this will replace the contents of that row, otherwise it will ad new row.

Add a row in the dataframe at index position using iloc[]

It will replace the row at index position 2 in dataframe dfObj with new row i.e.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.