loop on a dataframe rows in python

To loop through a dataframe row by row in Python using Pandas, there are several approaches:

  1. Using iterrows() method:
main.py
for index, row in dataframe.iterrows():
    # loop body
56 chars
3 lines

This method returns an iterator of index and row data as tuples, where the index is the index of the row and the row is a pandas series representing the row data.

  1. Using apply() method:
main.py
def func(row):
    # loop body

result = dataframe.apply(func, axis=1)
71 chars
5 lines

This method takes a function as an argument and applies it to each row of the dataframe. The axis=1 argument indicates that we are applying the function to rows.

  1. Using iloc[] indexer:
main.py
for i in range(len(dataframe)):
    row = dataframe.iloc[i]
    # loop body
76 chars
4 lines

This method uses integer-based indexing to access the rows of the dataframe.

Each of these methods has its own advantages and disadvantages, depending on the specific use case.

gistlibby LogSnag