How to add one row in an existing Pandas DataFrame?

In this article, we’ll perceive how to add another line of qualities to a current dataframe. This can be utilized when we need to embed another passage in our information that we may have missed adding before. There are various strategies to accomplish this. Presently we should see with the assistance of models how we can do this

To annex or add a column to DataFrame, make the new line as Series and use DataFrame.append() strategy. In this instructional exercise, we will figure out how to attach a line to a current DataFrame, with the assistance of illustrative model projects.

Example 1:

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

Example 2:

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)

Output:

add-row-to-existing-pandas-dataframe

Example 3:

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

Leave a Reply

Your email address will not be published. Required fields are marked *