How to iterate over Cells in Pandas DataFrame?
Pandas DataFrame - Iterate over Cell Values
In this tutorial, we will learn how to iterate over cell values of a Pandas DataFrame.
Method 1: Use a nested for loop to traverse the cells with the help of DataFrame Dimensions.
Method 2: Iterate over rows of DataFrame using DataFrame.iterrows(), and for each row, iterate over the items using Series.items().
Examples
1. Iterate over cells in DataFrame using DataFrame.shape and For loop
In this example, we will use a Nested For loop to iterate over the rows and columns of Pandas DataFrame. We will take the help of DataFrame.shape to get the number of rows and number of columns in the DataFrame. To access the cell value, we will use DataFrame.at().
Python Program
import pandas as pd
import numpy as np
df = pd.DataFrame(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
for i in range(df.shape[0]): #iterate over rows
for j in range(df.shape[1]): #iterate over columns
value = df.at[i, j] #get cell value
print(value, end="\t")
print()
Output
1 2 3
4 5 6
7 8 9
10 11 12
2. Iterate over Cells in a DataFrame using iterrows() method
In this example, we will use a nested For loop to iterate over the rows and columns of Pandas DataFrame.
To iterate over the rows, we will use DataFrame.iterrows(). And for each row, which we get as a Series, we will iterate over the items using Series.items().
Python Program
import pandas as pd
import numpy as np
df = pd.DataFrame(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
for rowIndex, row in df.iterrows(): #iterate over rows
for columnIndex, value in row.items():
print(value, end="\t")
print()
Output
1 2 3
4 5 6
7 8 9
10 11 12
We have access to row index and column index as well, while traversing through the cells in the DataFrame.
Summary
In this tutorial of Python Examples, we learned how to iterate over Cells in Pandas DataFrame, with examples.