Loop & Iterate Over Rows of pandas DataFrame in Python (Example Code)

In this tutorial, I’ll demonstrate how to loop over the rows of a pandas DataFrame in the Python programming language.

Setting up the Example

import pandas as pd                         # Load pandas library
my_df = pd.DataFrame({'A':range(10, 15),    # Construct pandas DataFrame
                      'B':['x', 'y', 'y', 'x', 'x'],
                      'C':range(15, 10, - 1)})
print(my_df)
#     A  B   C
# 0  10  x  15
# 1  11  y  14
# 2  12  y  13
# 3  13  x  12
# 4  14  x  11

Example: Apply for Loop to Rows of pandas DataFrame Using iterrows() Function

for i, row in my_df.iterrows():             # Use iterrows to print output
    print('This is my row at index position', i, ': A =', row['A'], '-', 'B =', row['B'], '-', 'C =', row['C'])
# This is my row at index position 0 : A = 10 - B = x - C = 15
# This is my row at index position 1 : A = 11 - B = y - C = 14
# This is my row at index position 2 : A = 12 - B = y - C = 13
# This is my row at index position 3 : A = 13 - B = x - C = 12
# This is my row at index position 4 : A = 14 - B = x - C = 11

Related Articles

Furthermore, you may want to read the other tutorials on my homepage:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top