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