/  Technology   /  Adding a new row to an existing Pandas DataFrame
How to add anew row to an existing Pandas DataFrame?

Adding a new row to an existing Pandas DataFrame

There may be situations where we need to insert a new data that we might have missed earlier. There are various ways to add a new row to our existing Pandas DataFrame. In this article we will see how to achieve this with the help of examples.

 

Example 1:

 

We can add a single row using DataFrame.loc. A row is added at the last in the DataFrame and by using len(DataFrame.index)to get the number of rows for determining the position at which we need to add the new row.

 

from IPython.display import display, HTML

import pandas as pd
from numpy.random import randint

dict = {'Name':['John', 'David', 'Robert', 'Georgia'],
    'English':[87, 91, 97, 95],
    'Chemistry':[83, 99, 84, 76]
    }

df = pd.DataFrame(dict)

display(df)

df.loc[len(df.index)] = ['Mary', 89, 93] 

display(df)

 

Output:

 

How to add anew row to an existing Pandas DataFrame?

 

Example 2:

 

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

 

from IPython.display import display, HTML

import pandas as pd
from numpy.random import randint

dict = {'Name':['John', 'David', 'Robert', 'Georgia'],
    'English':[87, 91, 97, 95],
    'Chemistry':[83, 99, 84, 76]
   }

df1 = pd.DataFrame(dict)
display(df1)

df2 = {'Name': 'Mary', 'English': 89, 'Chemistry': 93}
df = df1.append(df2, ignore_index = True)

display(df)

 

Output:

 

How to add anew row to an existing Pandas DataFrame?

 

Example 3:

 

We can also add multiple rows By using the pandas.concat() we can add multiple rows by creating a new DataFrame of all the rows that we need to add.

 

from IPython.display import display, HTML

import pandas as pd
from numpy.random import randint

dict = {'Name':['John', 'David', 'Robert', 'Georgia'],
    'English':[87, 91, 97, 95],
    'Chemistry':[83, 99, 84, 76]
   }

df1 = pd.DataFrame(dict)
display(df1)

dict = {'Name':['Mary', 'Christy'],
    'English':[89, 90],
    'Chemistry':[93, 81]
   }

df2 = pd.DataFrame(dict)
display(df2)

df3 = pd.concat([df1, df2], ignore_index = True)
df3.reset_index()
display(df3)

 

Output:

 

How to add anew row to an existing Pandas DataFrame?

 

 

Leave a comment