
In this post, you will learn –
1 . Iterate over rows using DataFrame.iterrows() method
2 . Iterate over rows using DataFrame.itertuples() method
3 . Using DataFrame.index method
4 . Using df.loc and df.iloc method
1 . Iterate over rows using DataFrame.iterrows() method
To iterate over rows in pandas, you can use the iterrows() method. This method returns the index as well as the rows of a pandas dataframe.
Let’s read a dataset to see it in action.
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/bprasad26/lwd/master/data/titanic.csv")
# select only 10 rows of data
df = df.head(10)
df

Let’s say that you want to iterate over the rows and select the index, Sex and Age data.
for index, row in df.iterrows():
print(index, row['Sex'], row['Age'])

2 . Iterate over rows using DataFrame.itertuples() method
Another method to iterate over rows in pandas is the DataFrame.itertuples() method. The main difference between this method and iterrows is that this method is faster than the iterrows method as well as it also preserve the data type of a column compared to the iterrows method which don’t as it returns a Series for each row but dtypes are preserved across columns. The itertuples method return a tuple where first value is the index number of the row and the remaining values are the values for each column. And to get the value from the tuple you need to use the getattr().
let’s see how to get the index, Sex, and Age using itertuples.
for row in df.itertuples():
print(getattr(row, 'Index'), getattr(row, 'Sex'), getattr(row, 'Age'))

3 . Using DataFrame.index method
You can also use the index method to iterate over rows in pandas. The df[‘Sex’][0] will return the first value from the sex column. The df[‘Sex’][1] will return the second value from the Sex column etc.
for index in df.index:
print(index, df['Sex'][index], df['Age'][index])

4 . Using loc and iloc method
You can also use the loc and iloc method.
Using loc method –
for index in range(len(df)):
print(index, df.loc[index, 'Sex'], df.loc[index, 'Age'])

Using iloc method –
iloc method is similar to the loc method, only difference is instead of using the name of the column, you need to use the column number. If you are not familiar with the loc and iloc method then read this post – How to select Rows and Columns in pandas.
for index in range(len(df)):
print(index, df.iloc[index, 4], df.iloc[index, 5])
