How to add new row in Pandas DataFrame
#1. Method:-
We can add a new row using the DataFrame.loc() function. This function will add the row at the end. We will use another function len(DataFrame.index) to get the position at which we want to add a new row.
import pandas as pd
dict= { ‘Name’ : [‘Raj’, “Ajay”, “Rahul”], ‘Percentage’ : [78,80,75] }
df= pd. DataFrame(dict)
print(df)
print(“After adding a new row”)
df.loc[ len(df.index) ] = [ “Vikas”, 70]
print(df)
Its output will be
一一一一一一一一一一一
0 Raj 78
一一一一一一一一一一一
0 Raj 78
#2. Method:-
We can add a new row using the DataFrame.append() function.This function will append the New Data Frame row at the end of the existing DataFrame.
import pandas as pd
import numpy as np
dict= { ‘Name’ : [‘Raj’, “Ajay”, “Rahul”], ‘Percentage’ : [78,80,75] }
df= pd. DataFrame(dict)
print(df)
print(“After adding a new row”)
df2= { “Name” : [“Vikas”], “Percentage” : 70}
df=df.append(df2, ignore_index= True)
print(df)
Its output will be
一一一一一一一一一一一
0 Raj 78
一一一一一一一一一一一
0 Raj 78
#3. Method:-
We can also add multiple number of news row using the pandas.concat() function.This function will append the New Data Frame rows at the end of the existing DataFrame, and create a new DataFrame.
import pandas as pd
import numpy as np
dict= { “Name” : [‘Raj’, “Ajay”, “Rahul”], “Percentage” : [78,80,75] }
df1= pd. DataFrame(dict)
print(df1)
dict= { “Name” : [“Keshu”, “Vipin” ], “Percentage” : [77,85 ] }
df2= pd. DataFrame(dict)
print(df2)
print(“After adding “)
df3 = pd.concat( [df1, df2 ], ignore_index= True)
df3.reset_index()
print(df3)
Its output will be
一一一一一一一一一一一
0 Raj 78
一一一一一一一一一一一
0 Keshu 77
一一一一一一一一一一一
0 Raj 78