How to iterate over rows in a DataFrame in Python’s Pandas library?

Sometimes, we want to iterate over rows in a DataFrame in Python’s Pandas library.

In this article, we’ll look at how to iterate over rows in a DataFrame in Python’s Pandas library.

How to iterate over rows in a DataFrame in Python’s Pandas library?

To iterate over rows in a DataFrame in Python’s Pandas library, we can use a for loop with the iterrows method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})

for index, row in df.iterrows():
    print(row['c1'], row['c2'])

We create dataframe with the pd.DataFrame class.

We pass in a dictionary with the columns of the dataframe.

Next, we call df.iterrows to return an iterable object with the index and row of the dataframe.

In the loop body, we print the entries of each row.

Therefore, we get:

10 100
11 110
12 120

printed.

Conclusion

To iterate over rows in a DataFrame in Python’s Pandas library, we can use a for loop with the iterrows method.