Categories
Python Answers

How to loop through DataFrames with Python Pandas?

Spread the love

Sometimes, we want to loop through DataFrames with Python Pandas.

In this article, we’ll look at how to loop through DataFrames with Python Pandas.

How to loop through DataFrames with Python Pandas?

To loop through DataFrames with Python Pandas, we can use the df.iterrows method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 3]})
for index, row in df.iterrows():
    print(index, row)

We create a DataFrame with pd.DataFrame with a dictionary as its argument.

Then we loop through the DataFrame rows returned by the df.iterrows method.

In the loop body, we unpack the index and row and print them.

Then we get:

0 col1    1
Name: 0, dtype: int64
1 col1    2
Name: 1, dtype: int64
2 col1    3
Name: 2, dtype: int64

from the print output.

Conclusion

To loop through DataFrames with Python Pandas, we can use the df.iterrows method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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