Pandas DataFrame Iterrows Method

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will explore the Python Pandas DataFrame.iterrows() method. This method allows us to iterate over the rows of a Pandas DataFrame, returning the index and data for each row.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Create a DataFrame

First, we need to create a DataFrame to work with. Let's create a simple DataFrame using the Pandas library.

#importing pandas as pd
import pandas as pd

#creating DataFrame
df=pd.DataFrame({"Name":["Navya","Vindya"],"Age":[25,24],"Education":["M.Tech","Ph.d"]},index=['id001', 'id002'])

Iterate over rows using the iterrows() method

To iterate over the rows of the DataFrame, we can use the iterrows() method. This method returns a generator object that contains a tuple of the index and data for each row.

#print the DataFrame
print("The DataFrame is:")
print(df)

#print the generator object
print("Iterate over rows:")
print(df.iterrows())

Use a for loop to access the rows

To access the index and data for each row, we can use a for loop. The row data can be accessed using the row_data variable, and the index can be accessed using the row_index variable.

#for loop to iterate over rows
print("Iterate over rows:")
for row_index, row_data in df.iterrows():
    print("Index:", row_index)
    print("Data:", row_data)

Accessing specific data from a row

We can also access a specific data from a row by specifying the index number. Let's print the value of the "Name" column for each row.

#for loop to access the "Name" column for each row
print("Accessing specific data:")
for row_index, row_data in df.iterrows():
    print("Name:", row_data['Name'])

Summary

In this lab, we learned how to use the iterrows() method in Pandas to iterate over the rows of a DataFrame. We explored how to access the index and data for each row using a for loop, and how to access specific data from a row. The iterrows() method is a useful tool for analyzing and manipulating data in a DataFrame.

Other Python Tutorials you may like