Iterate Over Row Index of pandas DataFrame in Python (Example Code)

In this Python programming tutorial you’ll learn how to loop through the index of a pandas DataFrame.

Preparing the Example

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

Example: Loop Over Indices of pandas DataFrame

for i, row in my_df.iterrows():           # Applying for loop
    print('At index', i, 'the column A has the value', row['A'])
# At index 0 the column A has the value 1
# At index 1 the column A has the value 2
# At index 2 the column A has the value 3
# At index 3 the column A has the value 4

Related Tutorials

You may find some further Python programming language tutorials on topics such as indices, naming data, and data inspection in the following list.

Leave a Reply

Your email address will not be published.

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