Pandas iterrows() Method Explained with Examples

Introduction

In this tutorial, we will go through the Pandas iterrows() method which is used to iterate over Pandas Data Frame. We will explore the syntax and various parameters of the iterrows function with practical examples to understand its usage.

Syntax of Pandas iterrows

The syntax of iterrows method is as below –

dataframe.iterrows()

  • There are no parameters for dataframe.iterrows() method. 

This method returns the following –

  • index: This is the index of the row that can be a label or a tuple of labels.
  • data: This is the data of the row that is a series.

Example of Pandas iterrows()

Example 1: Basic Usage

In this code snippet, we import Pandas, create a DataFrame, and use iterrows to iterate through each row, printing the Name and Age columns for each row.

# Import Pandas library
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 22]}
df = pd.DataFrame(data)

# Iterate over rows and print each row
for index, row in df.iterrows():
    print(f"Index: {index}, Name: {row['Name']}, Age: {row['Age']}")

Output

Index: 0, Name: Alice, Age: 25
Index: 1, Name: Bob, Age: 30
Index: 2, Name: Charlie, Age: 22

 

Example 2: Modifying Data

You can use iterrows() to modify data within the DataFrame. In this example, we will update the Age column by adding 5 to each value.

# Import Pandas library
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 22]}
df = pd.DataFrame(data)

# Modify the Age column using iterrows()
for index, row in df.iterrows():
    df.at[index, 'Age'] += 5

# Display the updated DataFrame
print(df)

Output

      Name  Age
0    Alice   30
1      Bob   35
2  Charlie   27

 

Example 3: Using Conditions

You can apply conditions to filter rows using iterrows(). In this example, we’ll identify and print rows where the age is greater than 25.

# Import Pandas library
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 22]}
df = pd.DataFrame(data)

# Print rows where Age > 25 using iterrows()
for index, row in df.iterrows():
    if row['Age'] > 25:
        print(f"Name: {row['Name']}, Age: {row['Age']}")

Output

Name: Bob, Age: 30

 

Follow Us

Leave a Reply

Your email address will not be published. Required fields are marked *