Pandas DataFrame Itertuples Method

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn about the Python Pandas DataFrame.iteruples() method. The iteruples() method in Pandas iterates over the rows of a DataFrame and returns each row as a named tuple. It is a useful method for iterating over and working with the rows of a DataFrame.

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.

Understand the Syntax

The syntax of the iteruples() method is as follows:

DataFrame.iteruples(index=True, name='Pandas')
  • index: It is a boolean value indicating whether to include the index as the first element of the tuple. The default value is True.
  • name: It is a string value representing the name of the returned named tuples. The default value is "Pandas". If set to None, regular tuples are returned instead of named tuples.

Iterate Over DataFrame Rows

In this step, we will create a DataFrame and use the iteruples() method to iterate over its rows. The method returns a map object, which can be used in a loop to iterate over each row as a named tuple.

## import pandas
import pandas as pd

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

## iterate over DataFrame rows
for row in df.iteruples():
    print(row)

Control Index and Tuple Naming

In this step, we will explore how to control the index and naming of the returned tuples. By default, the index is included as the first element of the tuple, and the tuples are named "Pandas". We can modify these settings by passing arguments to the iteruples() method.

## import pandas
import pandas as pd

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

## iterate over DataFrame rows without index and custom name
for row in df.iteruples(index=False, name='Rows'):
    print(row)

Summary

In this lab, we learned about the Pandas DataFrame.iteruples() method, which is useful for iterating over the rows of a DataFrame and accessing the values of each row. We saw how to use the method, control the inclusion of the index, and customize the naming of the returned tuples. This method can be helpful in various data analysis and manipulation tasks with Pandas DataFrames.

Other Python Tutorials you may like