Add row to Dataframe Python Pandas

In this Python Pandas tutorial, will learn how to add a row to Dataframe in Python using Pandas. Also, we will cover these topics.

  • Add rows to DataFrame Pandas in loop
  • Adding new row to DataFrame in Pandas
  • Adding new row to existing dataframe in Pandas
  • Python Pandas add row to empty DataFrame
  • Append rows to a DataFrame in Pandas
  • Adding row to DataFrame Python Pandas groupby

Add row to DataFrame Python Pandas

  • In Python, a dataframe is a two-dimensional data structure and if you want to analyze the DataFrame then you need to create a new DataFrame and add rows for declaring a DataFrame with specific elements.
  • Let us discuss how to add rows to Pandas DataFrame. There are various methods we can use to add rows in Pandas DataFrame.
    • By using DataFrame.append() method
    • By using iloc() method
    • By using concatenate method

Let’s have a look and understand these methods

Read Remove non-ASCII characters Python

By using DataFrame.append() method

  • In Pandas Dataframe the append() function is used to append rows from another Pandas Dataframe object. This method always returns a new DataFrame containing elements of both the Pandas DataFrame and does not modify the source DataFrame objects.
  • This method is always present in the Pandas library that provides the user to perform data analysis.

The Syntax of this method is here

DataFrame.append(
                 other,
                 ignore_index=False,
                 verify_integrity=False,
                 sort=False
                )
  • It consists of few parameters
    • other: This parameter specifies the data that going to append and also we can call DataFrame or Series.
    • ignore_index: if this argument is true then the resulting axis will be index labeled.
    • verify_integrity: This parameter specifies the boolean value, if it is true raise value error on creating a label by default it takes ‘false’ value.
    • Sort: This parameter is used to sort all the columns

Example:

Let’s take an example and check how to add a row to DataFrame

import pandas as pd

new_val = [('John', '9945', 'Germany'),
         ('William', '1456', 'Australia'),
         ('Micheal', '118', 'England'),
         ('Oliva', '934', 'Spain'),
         ('Elijah', '167', 'Paris')]

result = pd.DataFrame(new_val,
                     columns=['Student_name', 'Student_id', 'Student_city'])

print(result)
newDfObj = result.append({'Student_name': 'Potter',
                         'Student_id': '109',
                         'Student_city': 'Bangladesh'}, ignore_index=True)

print(newDfObj)

In the above code first, we have created a list of tuples ‘new_val’ and then declare a dataframe object ‘result’ in which we have assigned the column names. Now we want to add a row in an existing dataframe to do this we have used DataFrame.append() method and pass the dictionary as a new row of DataFrame.

Here is the execution of the following given code

Add row to DataFrame Python Pandas
Add row to DataFrame Python Pandas

By using iloc() method

In Python, the iloc() method is used for selecting specific rows. It accepts only integer values and it helps the user to select a value that belongs to a specific row and column.

Syntax:

Here is the Syntax of the dataframe. iloc() method

property DataFrame.iloc()

Source Code:

import pandas as pd

new_val = [('John', '9945', 'Germany'),
         ('William', '1456', 'Australia'),
         ('Micheal', '118', 'England'),
         ('Oliva', '934', 'Spain'),
         ('Elijah', '167', 'Paris')]


m = pd.DataFrame(new_val,
                     columns=['Student_name', 'Student_id', 'Student_city'])

m.iloc[1] = ['George', '468', 'Ireland']

print(m)

Here is the Output of the following given code

Add row to DataFrame Python Pandas
Add row to DataFrame Python Pandas

By using Concatenate method

In this program, we will add multiple rows by using pandas.Concat() method. In Pandas DataFrame we can easily be combining series or dataframe with various datasets by using Pandas.Concat() method.

Syntax:

Here is the Syntax of Pandas.Concat() method

Pandas.Concat
             (
              objs,
              axis=0,
              join='outer',
              ignore_index=False,
              Keys=None,
              Levels=None,
              names=None,
              Verify_integrity=False,
              Sort=False,
              Copy=True
             )

Example:

import pandas as pd
import numpy as np

Employee_info1 = {'Employee_name':['Micheal', 'William', 'Bob', 'Oliva'],
		'Employee_id':[834, 156, 349, 168],
		'Employee_age':[23, 37, 46, 26]
	}

df1 = pd.DataFrame(Employee_info1)


Employee_info2 = {'Employee_name':['Elijah', 'John'],
		'Employee_id':[78, 118],
		'Employee_age':[17, 19]
	}

df2 = pd.DataFrame(Employee_info2)
new_val = pd.concat([df1, df2], ignore_index = True)
new_val.reset_index()

print(new_val)

In the above code first, we have created a dictionary ‘Employee_info1’ and then declare a dataframe object in which we have passed the dictionary as an argument. Similarly, we have created another dictionary ‘Employee_info2’.

Now we want to concatenate two different Dataframe and store the result into ‘new_val’. Once you will print the ‘new_val’ then the output will display new rows in the DataFrame.

Here is the Screenshot of the following given code

Add row to DataFrame Python Pandas
Add row to DataFrame Python Pandas

Read: Check If DataFrame is Empty in Python Pandas

Add rows to DataFrame Pandas in loop

  • Here we can see how to add rows to DataFrame by using for loop method
  • By using for loop we can iterate over a list of rows and inside a loop combine the column name as keys elements with the data as values. In Python, the zip() method accepts items and append them into a single tuple.

Source Code:

import pandas as pd
 
new_col = ['Integer value']
new_empt_list = []
b = 123
 
for m in range(8):
    new_empt_list.append([b])
    b = b + 1
df = pd.DataFrame(new_empt_list, columns=new_col)
print(df)

In the above code first, we create a variable and assign a column name in the list.

Here is the implementation of the following given code

Add rows to DataFrame Pandas in loop
Add rows to DataFrame Pandas in a loop

Read: Python Pandas replace multiple values 

Adding new row to DataFrame in Pandas

  • In this program, we will discuss how to add a new row in the Pandas DataFrame.
  • By using the append() method we can perform this particular task and this function is used to insert one or more rows to the end of a dataframe.
  • This method always returns the new dataframe with the new rows and containing elements of both the Pandas DataFrame and it does not modify the source DataFrame objects.

Source Code:

import pandas as pd

new_dictionary = {'Student_name': ['Noah', 'Lijah'],
	'Desgination': ['Developer', 'Tester'],
	'student_id': [178, 199]}

df = pd.DataFrame(new_dictionary)
result = pd.Series(data={'Student_name':'George', 'Desgination':'Gamer', 'student_id':658}, name='x')
df = df.append(result, ignore_index=False)
print(df)

In the above code first, we have created a dictionary ‘new_dictionary’ and then declare a dataframe object ‘result’ in which we have assigned the dictionary name.

Now we want to add a row in an existing dataframe to do this we have used DataFrame.append() method and pass the dictionary as a new row of DataFrame.

You can refer to the below Screenshot

Adding new row to DataFrame in Pandas
Adding a new row to DataFrame in Pandas

Read: Python Pandas Drop Rows

Adding new row to existing dataframe in Pandas

  • Let us see how to add a new row in the existing Pandas DataFrame.
  • To perform this particular task we can use the concept of append() function and this method will help the user to add a new row in the existing DataFrame.

Example:

import pandas as pd


my_dictionary = {'Fruit_name':['Apple', 'Litchi', 'Cherry', 'Banana'],
		'new_val':[189, 578, 289, 134],
		
	}

df = pd.DataFrame(my_dictionary)
df2 = {'Fruit_name': 'Grapes', 'new_val': 167}
df = df.append(df2, ignore_index = True)
print(df)

Here is the output of the following given code

Adding new row to DataFrame in Pandas
Adding a new row to DataFrame in Pandas

Read: How to Convert Pandas DataFrame to a Dictionary

Python Pandas add row to empty DataFrame

  • In this program, we will discuss how to declare an empty DataFrame and append rows in it.
  • In this example we have the column names of our dataframe but we don’t have any values or data in the DataFrame. So Now first, we will create an empty dataframe with only specific column names.
  • Now append rows in Empty dataframe by adding dictionaries in which we have assigned key-value pair elements. After creating a datafarme pass ‘ignore_index=True’ as a parameter in it.

Source Code:

import pandas as pd


new_val = pd.DataFrame(columns = ['emp_id', 'emp_age', 'emp_city'])
print(new_val)

new_val = new_val.append({'emp_id' : 876, 'emp_age' : 29, 'emp_city' : 'Germany'},
				ignore_index = True)
new_val = new_val.append({'emp_id' : 115, 'emp_age' : 34, 'emp_city' : 'Uganda'},
				ignore_index = True)
new_val = new_val.append({'emp_id' : 1178, 'emp_age' : 16, 'emp_city' : 'Russia'},
				ignore_index = True)
print(new_val)

Here is the Screenshot of the following given code

Python Pandas add row to empty DataFrame
Python Pandas add a row to empty DataFrame

Read: How to use Pandas drop() function in Python

Append rows to a DataFrame in Pandas

  • Here we can see how to append rows in a pandas DataFrame.
  • By using append() function we can insert specific rows in a Pandas DataFrame.

Source Code:

import pandas as pd

new_val = [('John', '9945', 'Germany'),
         ('William', '1456', 'Australia'),
         ('Micheal', '118', 'England'),
         ('Oliva', '934', 'Spain'),
         ('Elijah', '167', 'Paris')]

new_output = pd.DataFrame(new_val,
                     columns=['Student_name', 'Student_id', 'Student_city'])

print(new_output)
m = new_output.append({'Student_name': 'Potter',
                         'Student_id': '109',
                         'Student_city': 'Bangladesh'}, ignore_index=True)

print(m)

In the above code first, we have created a list of tuples ‘new_val’ and then declare a dataframe object ‘result’ in which we have assigned the column names.

Now we want to add a row in an existing dataframe to do this we have used DataFrame.append() method and pass the dictionary as a new row of DataFrame.

You can refer to the below Screenshot

Append rows to a DataFrame in Pandas
Append rows to a DataFrame in Pandas

Read: Groupby in Python Pandas

Adding row to DataFrame Python Pandas groupby

  • Let us see how to add a row in a DataFrame by using groupby method.
  • In Python, the group-by function combine the result together and also we can split the data into separate groups based on the condition. This function can be used to group a large amounts of data.

Syntax:

Here is the Syntax of the groupby method

DataFrame.groupby
                (
                 by=None,
                 axis=0,
                 level=None,
                 as_index=True,
                 sort=True,
                 group_keys=True,
                 Squeeze=Nodefault.no_default,
                 observed=False,
                 dropna=True
                )

Example:

import pandas as pd
  
df = pd.read_csv("test1.csv")
new_val = df.groupby(['China', 'Egypt'])
b= new_val.first()
print(b)

Here is the execution of the following given code

Adding row to DataFrame Python Pandas groupby
Adding a row to DataFrame Python Pandas groupby

You may also like to read the following articles.

In this Python Pandas tutorial, we have learned how to add a row to Dataframe in Python using Pandas. Also, we have covered these topics.

  • Add rows to DataFrame Pandas in loop
  • Adding new row to DataFrame in Pandas
  • Adding new row to existing dataframe in Pandas
  • Python Pandas add row to empty DataFrame
  • Append rows to a DataFrame in Pandas
  • Adding row to DataFrame Python Pandas groupby