Using pandas append() method within for loop

Given a pandas dataframe, we have to learn how to use pandas append() method within for loop? By Pranit Sharma Last updated : October 02, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given a DataFrame, we will append rows to the DataFrame with for loop, but in this way, DataFrame will be empty at the end. One way is to create an Array and then call for the DataFrame method but this will fail when we will deal with a large amount of data.

Pandas append() method within for loop

The append() function inserts an element into a pre-defined list. The element will be added to the last position of the list rather than being returned to a new list.

Every time we call the append() method; pandas returns a copy of the original DataFrame plus a new row that has been appended. For this purpose, we will first create an empty DataFrame and then we will use the append() method within for loop.

Let us understand with the help of an example,

Python program to use pandas append() method within for loop

# Import pandas as pd
import pandas as pd

# Import numpy as np
import numpy as np

# Creating an empty DataFrame
df = pd.DataFrame([])

# Using for loop for inserting rows
for i in np.arange(0, 5):
    if i % 2 == 0:
        df = df.append(pd.DataFrame({'A': i, 'B': i + 1}, index=[0]), ignore_index=True)
    else:
        df = df.append(pd.DataFrame({'A': i}, index=[0]), ignore_index=True)

# Display created DataFrame
print("Created DataFrame:\n",df)

Output

The output of the above program is:

Example: pandas append() method within for loop

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.