How to iterate over rows in a DataFrame in Pandas

Created by waitingkuoLinked to 7.8m issues across 267 teams


Using the DataFrame.iterrows() method, you can iterate over the rows of a DataFrame in Pandas. To do this, first create a DataFrame with the desired columns and values. Then, use the reset_index() method to ensure that the indexes of the DataFrame correspond to the number of rows. Finally, use the iterrows() method to iterate over the rows of the DataFrame. This method yields both the index and row (as a Series) of each row. For example, the following code will print the values of the columns c1 and c2 for each row of the DataFrame:

import pandas as pd df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]}) df = df.reset_index() # make sure indexes pair with number of rows for index, row in df.iterrows(): print(row['c1'], row['c2'])

This will output the following:

10 100 11 110 12 120