Iterate over pandas dataframe using itertuples

Learn, how can we iterate over pandas dataframe using itertuples? By Pranit Sharma Last updated : October 03, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Iterating over pandas dataframe using itertuples

Iterating refers to accessing each element at least once using any iterator. The iterator here can be a loop (for or while) inside which we can use an incremented variable and access each element of any data set.

We will use pandas.DataFrame.itertuples() method for accessing each element of DataFrame. This is a method that us used to iterate over DataFrame rows as named tuples.

The syntax of itertuples() method is:

DataFrame.itertuples(index=True, name='Pandas')

The parameters of itertuples() method are:

  • index: default True, if True, return the index as the first element of the tuple.
  • name: The name of the returned namedtuples or None to return regular tuples.

Let us understand with the help of an example,

Python program to iterate over pandas dataframe using itertuples

# Importing pandas package
import pandas as pd

# Import numpy package
import  numpy as np

# Creating a dictionary
d = np.random.randint(1,3, (10,5))

# Creating a DataFrame
df = pd.DataFrame(d,columns=['A','B','C','D','E'])

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Using itertuples
for i, row in enumerate(df.itertuples(), 1):
    print(i, row.B)


The output of the above program is:

Example: Iterate over pandas dataframe using itertuples

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.