You can use the following basic syntax to iterate over rows in a pandas DataFrame:
for index, row in df.iterrows():
print(row)
The following examples show how to use this syntax in practice with the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19], 'assists': [5, 7, 7, 9, 12], 'rebounds': [11, 8, 10, 6, 6]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6
Example 1: Iterate Over All Rows in DataFrame
The following code shows how to iterate over every row in a pandas DataFrame:
for index, row in df.iterrows():
print(row)
points 25
assists 5
rebounds 11
Name: 0, dtype: int64
points 12
assists 7
rebounds 8
Name: 1, dtype: int64
points 15
assists 7
rebounds 10
Name: 2, dtype: int64
points 14
assists 9
rebounds 6
Name: 3, dtype: int64
points 19
assists 12
rebounds 6
Name: 4, dtype: int64
We can also use the following syntax to iterate over every row and print just the index of each row:
for index, row in df.iterrows():
print(index)
0
1
2
3
4
Example 2: Iterate Over Specific Rows
The following syntax shows how to iterate over specific rows in a pandas DataFrame:
#iterate over first three rows only
for index, row in df.iloc[0:3, :].iterrows():
print(row)
points 25
assists 5
rebounds 11
Name: 0, dtype: int64
points 12
assists 7
rebounds 8
Name: 1, dtype: int64
points 15
assists 7
rebounds 10
Name: 2, dtype: int64
You can find the complete documentation for the iterrows() function here.
Additional Resources
How to Add Rows to a Pandas DataFrame
How to Count Number of Rows in Pandas DataFrame
How to Select Unique Rows in a Pandas DataFrame