banner



How To Add A Row To Pandas Dataframe

How to add i row in an existing Pandas DataFrame?

In this article, we'll encounter how to add a new row of values to an existing dataframe. This can be used when we want to insert a new entry in our data that we might have missed adding earlier. There are different methods to achieve this. Now let's meet with the help of examples how we can do this

Example 1:

We tin can add a single row using DataFrame.loc. Nosotros can add the row at the last in our dataframe. We can get the number of rows using len(DataFrame.index) for determining the position at which we demand to add together the new row.

from IPython.brandish import display, HTML

import pandas equally 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.alphabetize)] = [ 'Amy' , 89 , 93 ]

display(df)

Output:

add-row-to-existing-pandas-dataframe

Example 2:

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

from IPython.display import display, HTML

import pandas every bit pd

import numpy as np

dict = { 'Proper name' :[ 'Martha' , 'Tim' , 'Rob' , 'Georgia' ],

'Maths' :[ 87 , 91 , 97 , 95 ],

'Science' :[ 83 , 99 , 84 , 76 ]

}

df = pd.DataFrame( dict )

brandish(df)

df2 = { 'Name' : 'Amy' , 'Maths' : 89 , 'Scientific discipline' : 93 }

df = df.append(df2, ignore_index = Truthful )

display(df)

Output:

add-row-to-existing-pandas-dataframe

Example 3:

Nosotros can also add multiple rows using the pandas.concat() past creating a new dataframe of all the rows that we need to add and so appending this dataframe to the original dataframe.

from IPython.display import brandish, HTML

import pandas equally 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 = { 'Proper noun' :[ '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 A Row To Pandas Dataframe,

Source: https://www.geeksforgeeks.org/how-to-add-one-row-in-an-existing-pandas-dataframe/

Posted by: kelleyandon1984.blogspot.com

0 Response to "How To Add A Row To Pandas Dataframe"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel