The Wayback Machine - https://web.archive.org/web/20240530021430/https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
Open In App

Different ways to iterate over rows in Pandas Dataframe

Last Updated : 29 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will cover how to iterate over rows in a DataFrame in Pandas.

How to iterate over rows in a DataFrame in Pandas

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. 

Let’s see the Different ways to iterate over rows in Pandas Dataframe :

Method 1: Using the index attribute of the Dataframe.

Python3




# import pandas package as pd
import pandas as pd
 
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit',
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age',
                                 'Stream', 'Percentage'])
 
print("Given Dataframe :\n", df)
 
print("\nIterating over rows using index attribute :\n")
 
# iterate through each row and select
# 'Name' and 'Stream' column respectively.
for ind in df.index:
    print(df['Name'][ind], df['Stream'][ind])


Output:

Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70

Iterating over rows using index attribute :

Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology

Method 2: Using loc[] function of the Dataframe. 

Python3




# import pandas package as pd
import pandas as pd
 
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit',
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age',
                                 'Stream',
                                 'Percentage'])
 
print("Given Dataframe :\n", df)
 
print("\nIterating over rows using loc function :\n")
 
# iterate through each row and select
# 'Name' and 'Age' column respectively.
for i in range(len(df)):
    print(df.loc[i, "Name"], df.loc[i, "Age"])


Output:

Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70

Iterating over rows using loc function :

Ankit 21
Amit 19
Aishwarya 20
Priyanka 18

Method 3: Using iloc[] function of the DataFrame. 

Python3




# import pandas package as pd
import pandas as pd
 
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit',
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age',
                                 'Stream', 'Percentage'])
 
print("Given Dataframe :\n", df)
 
print("\nIterating over rows using iloc function :\n")
 
# iterate through each row and select
# 0th and 2nd index column respectively.
for i in range(len(df)):
    print(df.iloc[i, 0], df.iloc[i, 2])


Output:

Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70

Iterating over rows using iloc function :

Ankit Math
Amit Commerce
Aishwarya Arts
Priyanka Biology
​

 Method 4: Using iterrows() method of the Dataframe. 

Python3




# import pandas package as pd
import pandas as pd
 
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit',
                 'Aishwarya', 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce',
                   'Arts', 'Biology'],
        'Percentage': [88, 92, 95, 70]}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age',
                                 'Stream', 'Percentage'])
 
print("Given Dataframe :\n", df)
 
print("\nIterating over rows using iterrows() method :\n")
 
# iterate through each row and select
# 'Name' and 'Age' column respectively.
for index, row in df.iterrows():
    print(row["Name"], row["Age"])


Output:

Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70

Iterating over rows using iterrows() method :

Ankit 21
Amit 19
Aishwarya 20
Priyanka 18

Method 5: Using itertuples() method of the Dataframe. 

Python3




# import pandas package as pd
import pandas as pd
 
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 'Aishwarya',
                 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce', 'Arts',
                   'Biology'],
        'Percentage': [88, 92, 95, 70]}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age',
                                 'Stream',
                                 'Percentage'])
 
print("Given Dataframe :\n", df)
 
print("\nIterating over rows using itertuples() method :\n")
 
# iterate through each row and select
# 'Name' and 'Percentage' column respectively.
for row in df.itertuples(index=True, name='Pandas'):
    print(getattr(row, "Name"), getattr(row, "Percentage"))


Output:

Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70

Iterating over rows using itertuples() method :

Ankit 88
Amit 92
Aishwarya 95
Priyanka 70
​

Method 6: Using apply() method of the Dataframe. 

Python3




# import pandas package as pd
import pandas as pd
 
# Define a dictionary containing students data
data = {'Name': ['Ankit', 'Amit', 'Aishwarya',
                 'Priyanka'],
        'Age': [21, 19, 20, 18],
        'Stream': ['Math', 'Commerce', 'Arts',
                   'Biology'],
        'Percentage': [88, 92, 95, 70]}
 
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age', 'Stream',
                                 'Percentage'])
 
print("Given Dataframe :\n", df)
 
print("\nIterating over rows using apply function :\n")
 
# iterate through each row and concatenate
# 'Name' and 'Percentage' column respectively.
print(df.apply(lambda row: row["Name"] + " " +
               str(row["Percentage"]), axis=1))


Output:

Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Arts 95
3 Priyanka 18 Biology 70

Iterating over rows using apply function :

0 Ankit 88
1 Amit 92
2 Aishwarya 95
3 Priyanka 70
dtype: object


Previous Article
Next Article

Similar Reads

How to iterate over rows in Pandas Dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Let’s see the how to iterate over rows in Pandas Dataframe using iterrows() and itertuples() :Method #1: Using the DataFrame.iterrows() m
2 min read
How to Iterate over rows and columns in PySpark dataframe
In this article, we will discuss how to iterate rows and columns in PySpark dataframe. Create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf
6 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
Pandas DataFrames facilitate column-wise iteration, allowing convenient access to elements in each column. In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Creating Pandas DataframeIn this article, we will use this Dataframe that we have created by using the Pandas package. C/C++ Code # import panda
5 min read
Iterating over rows and columns in Pandas DataFrame
Iteration is a general term for taking each item of something, one after another. Pandas DataFrame consists of rows and columns so, to iterate over dataframe, we have to iterate a dataframe like a dictionary. In a dictionary, we iterate over the keys of the object in the same way we have to iterate in dataframe. In this article, we are using "nba.c
6 min read
Different ways to create Pandas Dataframe
Pandas DataFrame is a 2-dimensional labeled data structure like a table with rows and columns. The size and values of the DataFrame are mutable, i.e., can be modified. DataFrame is mostly used in data analysis and data manipulation. It lets you store data in tabular form like SQL database, MS Excel, or Google Sheets, making it easier to perform ari
6 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Iterate over characters of a string in Python
In Python, while operating with String, one can do multiple operations on it. Let's see how to iterate over the characters of a string in Python. Example #1: Using simple iteration and range() C/C++ Code # Python program to iterate over characters of a string # Code #1 string_name = "geeksforgeeks" # Iterate over the string for el
3 min read
Iterate over words of a String in Python
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = "GeeksforGeeks is a computer science portal for Geeks" Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks" Output: Geeks for Geeks Method 1: Using split() Using
4 min read