Pandas iterate over rows – Python


Python pandas provides iterrows() function which can be used to iterate over rows in dataframe. Consider this example –

import pandas as pd
df = pd.DataFrame({'marvel': ['Thor', 'Hulk'], 'dc': ['Flash', 'Cyborg']})

In order to iterate row by row, we need to run a loop using iterrows() function. For now, our dataframe has 2 lists – marvel and dc. When we run iterrows(), it will fetch Thor & Flash in first iteration and Hulk & Cyborg in second iteration.

Here is the code –

for index, row in df.iterrows():
    print(row['marvel'], row['dc'])

    Tweet this to help others

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

How to rename columns in Pandas Python?

Table of Contents Hide 1. Assigning new columns to attribute .columns2. Making columns copy, change required one and reassign3. Using rename() function4. Using set_axis() function5. Using lambda functionLive DemoRelated Posts:…
View Post