In this post, we are going to learn about 7 ways to Add row in Pandas DataFrame.These ways can be used to append or insert data to an existing dataframe or empty dataframe.
1. append() method to Add data row by row in Pandas Dataframe
The Pandas Append() method appends rows of other dataframe at the end of the given dataframe. It does not change the original dataframe instead returns a new object. In this example, new rows are initialized as a Python dictionary, and mandatory to pass ignore_index=True, otherwise by setting ignore_index=False, will raise an error.
TypeError(“Can only append a dict if ignore_index=True”) TypeError: Can only append a dict if ignore_index=True
import pandas as pd
df_studs = pd.DataFrame()
new_row = {'Name':'Dev','Subj':'comp','Marks':100}
new_row2 = {'Name':'Jack','Subj':'Math','Marks':100}
df_studs = df_studs.append(new_row, ignore_index=True)
df_studs = df_studs.append(new_row2, ignore_index=True)
print(f'\n{df_studs}')
Output
Marks Name Subj
0 100.0 Dev comp
1 100.0 Jack Math
2. concat() method to Add data row by row
The pandas concat() method “Concatenate pandas objects along a particular axis with optional set logic along the other axes.
import pandas as pd
import numpy as np
df_studs = pd.DataFrame()
new_row = pd.DataFrame(data=np.array([['jack','Math',100]]), columns=['Name','Subj','Marks'])
new_row1 = pd.DataFrame(data=np.array([['Maxi','Phy',100]]), columns=['Name','Subj','Marks'])
df_studs = pd.concat([df_studs,new_row,new_row1], ignore_index=True)
print(df_studs)
Output
Name Subj Marks
0 jack Math 100
1 Maxi Phy 100
3. loc() attribute to Add row at specific Index
The loc() attribute of pandas dataframe is used to access a group of rows and columns by labels or boolean array, We can use DataFrame.loc() to access particular cell by row index and column label.
We can get the numbers of rows by using the len(dataframe. index) method to find out the index at which we have to insert a new row.
In this example, we have created an empty data frame(df_studs). To get the length we are using the len() method to find the index on which we have to insert rows.
Python Program to add elements to empty DataFrame
import pandas as pd
df_studs = pd.DataFrame()
df_studs = pd.DataFrame(columns=['Name','Subj','Marks'])
df_studs.loc[len(df_studs.index)] = ['Jack', 'Math', 93]
df_studs.loc[len(df_studs.index)] = ['Rack', 'Math', 93]
print(f'\n{df_studs}')
Output
Name Subj Marks
0 Jack Math 93
1 Rack Math 93
4. Loc[] to insert list as a row at specific index
We can append a list to the dataframe on the index label in the dataframe by assigning the list to loc[] attribute.
In this example, we are assigning a list at index label loc[“Row_1”] to append a row to the dataframe.
import pandas as pd
df_studs = pd.DataFrame(columns=['Name','Subj','Marks'],index=['Row_1', 'Row_2', 'Row_3'])
df_studs.loc['Row_1'] = ['jack', 'Math', 100]
print(df_studs)
Output
Name Subj Marks
Row_1 jack Math 100
Row_2 NaN NaN NaN
Row_3 NaN NaN NaN
5. iloc[] to add a row to index postion
We can use the Dataframe iloc[] attribute to add a row at a specific index position in the dataframe.In this example, we are inserting a row at index position 0. We can insert rows at the top or bottom or any index of the dataframe.
import pandas as pd
df_studs = pd.DataFrame(columns=['Name','Subj','Marks'],index=['Row_1', 'Row_2', 'Row_3'])
df_studs.iloc[0] = ['jack', 'Math', 100]
print(df_studs)
Output
Name Subj Marks
Row_1 jack Math 100
Row_2 NaN NaN NaN
Row_3 NaN NaN NaN
6. Add Pandas series as a row to Dataframe
In this example, we are appending a series object(ser_obj) in the dataframe to add a new row to DataFrame.
import pandas as pd
df_studs = pd.DataFrame(columns=['Name','Subj','Marks'])
ser_obj = pd.Series( ['jack', 'Math', 100],
index=df_studs.columns )
result_df = df_studs.append(ser_obj,
ignore_index=True)
print(result_df)
Output
Name Subj Marks
0 jack Math 100
7. Add mutiple rows as dictionary
In this example, we are adding a dictionary s(mydict) in the Panda Dataframe. in which values of the dictionary keys( ‘Name’, ‘Subj’, ‘Marks’) are as a list.
import pandas as pd
mydict = {'Name':['Dev','Jack','Rack'],'Subj':['comp','Math','Phy'],'Marks':[100,100,98]}
df_studs = pd.DataFrame(mydict)
print(f'\n{df_studs}')
Output
Name Subj Marks
0 Dev comp 100
1 Jack Math 100
2 Rack Phy 98
Summary
In this post, we have learned multiple ways to Add data row by row in Pandas DataFrame that can be used for any empty dataframe or existing dataframe at a specified index or append dictionary and list to dataframe as a row.