How to iterate over rows in a DataFrame in Pandas?


To iterate rows in a DataFrame in Pandas, we can use the iterrows() method, which will iterate over DataFrame rows as (index, Series) pairs.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Iterate df using df.iterrows() method.

  • Print each row with index.

Example

 Live Demo

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)
print "Given DataFrame:
", df for index, row in df.iterrows():    print "Row ", index, "contains: "    print row["x"], row["y"], row["z"]

Output

Given DataFrame:
   x   y   z
0  5   4   4
1  2   1   1
2  1   5   5
3  9  10   0
Row 0 contains:
5 4 4
Row 1 contains:
2 1 1
Row 2 contains:
1 5 5
Row 3 contains:
9 10 0

Updated on: 30-Aug-2021

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements