Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
Python | Pandas Series.iteritems()
Next article icon

Pandas DataFrame iterrows() Method

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

iterrows() method in Pandas is a simple way to iterate over rows of a DataFrame. It returns an iterator that yields each row as a tuple containing the index and the row data (as a Pandas Series). This method is often used in scenarios where row-wise operations or transformations are required. Example:

[GFGTABS]
Python

import pandas as pd  df = pd.DataFrame({'Name': ['Aman', 'Raj'], 'Age': [25, 32]})  # Iterating through the DataFrame for index, row in df.iterrows():     print(f"Index: {index}, Name: {row['Name']}, Age: {row['Age']}") 


[/GFGTABS]

Output
Index: 0, Name: Aman, Age: 25 Index: 1, Name: Raj, Age: 32 

Explanation: This code uses iterrows() to iterate over each row of the DataFrame and prints the index, Name, and Age for each row.

Syntax

DataFrame.iterrows()

Parameters: It does not take any parameters.

Return Value: It returns an iterator that yields each row as a tuple containing the index and the row data (as a Pandas Series).

Examples of iterrows() Method

Example 1. Iterating Over the First Row of a DataFrame Using iterrows()

Let’s understand how to iterate over the rows of DataFrame using iterrows() method of Pandas library. In the below example, we use Pandas DataFrame.iterrows() to iterate over numeric DataFrame rows:

[GFGTABS]
Python

import pandas as pd  # Creating a DataFrame with column names df = pd.DataFrame(     [[2, 2.5, 100, 4.5, 8.8, 95]],     columns=['int', 'float', 'int', 'float', 'float', 'int'] )  # Get the first row as a Series using iterrows() itr = next(df.iterrows())[1] print(itr) 


[/GFGTABS]

Output:

Pandas DataFrame iterrows example output

Explanation: This code creates a DataFrame and uses iterrows() to get the first row as a Series. next(df.iterrows())[1] retrieves and prints the first row of the DataFrame.

Example 2. Calculating Total Sales for Each Product Using iterrows()

In the example, we iterate over the rows involving multiple columns using Pandas DataFrame.iterrows() function.

[GFGTABS]
Python

import pandas as pd  df = pd.DataFrame({     'Product': ['A', 'B', 'C'],     'Price': [10, 20, 15],     'Quantity': [100, 50, 200] })  # Calculate total sales for each product for index, row in df.iterrows():     total_sales = row['Price'] * row['Quantity']     print(f"Product {row['Product']} generated ${total_sales} in sales.") 


[/GFGTABS]

Output
Product A generated $1000 in sales. Product B generated $1000 in sales. Product C generated $3000 in sales. 

Explanation: This code iterates through each row of the DataFrame, calculates the total sales (Price * Quantity) for each product, and prints the result.

Example 3. Adding New Columns Using Iteration

We can also, add the new column in this case we’ll add ‘Category’ column using df.at[index, ‘Category’] to assign a value for each row based on a condition.

[GFGTABS]
Python

import pandas as pd  df = pd.DataFrame({     'Name': ['Aman', 'Raj', 'Ayush'],     'Age': [25, 32, 37] })  # Adding a new column based on conditions for index, row in df.iterrows():     if row['Age'] > 30:         df.at[index, 'Category'] = 'Senior'     else:         df.at[index, 'Category'] = 'Junior'  print(df) 


[/GFGTABS]

Output
    Name  Age Category 0   Aman   25   Junior 1    Raj   32   Senior 2  Ayush   37   Senior 

Explanation: This code iterates through each row of the DataFrame, checks the Age, and assigns a Category (Senior or Junior) based on the age.

How does iterrows() Method Work?

In simple terms, iterrows() is a generator function. It generates a sequence of (index, row) pairs as you loop through your DataFrame. The index is the row label (or the row number if no custom index is set), and row is a Series object where each value corresponds to a column in that row. Behind the scenes, iterrows() works by iterating over the DataFrame one row at a time:

  1. Row-by-Row Iteration: It loops over each row in the DataFrame, starting from the first row to the last.
  2. Index and Row: During each iteration, it returns the index (row label) and the row data as a Series.
  3. Efficient for Small Datasets: This method is effective when you need to process rows individually, but it’s not the fastest for large datasets.

Related Articles:

  • Pandas Tutorial
  • Pandas DataFrame
  • Generators in Python
  • Tuple Operations in Python


Next Article
Python | Pandas Series.iteritems()
author
vanshgaur14866
Improve
Article Tags :
  • AI-ML-DS
  • Pandas
  • Python
  • AI-ML-DS With Python
  • Pandas-DataFrame-Methods
  • Python pandas-dataFrame
  • Python-pandas
Practice Tags :
  • python

Similar Reads

  • Pandas DataFrame corr() Method
    Pandas dataframe.corr() is used to find the pairwise correlation of all columns in the Pandas Dataframe in Python. Any NaN values are automatically excluded. To ignore any non-numeric values, use the parameter numeric_only = True. In this article, we will learn about DataFrame.corr() method in Pytho
    4 min read
  • Pandas query() Method
    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 that makes importing and analyzing data much easier. Analyzing data requires a lot of filtering operations. Pandas Dataframe provide many
    2 min read
  • Python | Pandas dataframe.insert()
    Pandas insert method allows the user to insert a column in a data frame or series(1-D Data frame). A column can also be inserted manually in a data frame by the following method, but there isn't much freedom here. For example, even column location can't be decided and hence the inserted column is al
    8 min read
  • Pandas dataframe.sum()
    DataFrame.sum() function in Pandas allows users to compute the sum of values along a specified axis. It can be used to sum values along either the index (rows) or columns, while also providing flexibility in handling missing (NaN) values. Example: [GFGTABS] Python import pandas as pd data = { 'A
    4 min read
  • Pandas DataFrame mean() Method
    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. Pandas DataFrame mean() Pandas dataframe.mean() function returns the mean of the value
    2 min read
  • Python | Pandas dataframe.median()
    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. Pandas dataframe.median() function return the median of the values for the requested a
    2 min read
  • Python | Pandas Series.std()
    Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.std() function return sample
    2 min read
  • Apply function to every row in a Pandas DataFrame
    Python is a great language for performing data analysis tasks. It provides a huge amount of Classes and functions which help in analyzing and manipulating data more easily. In this article, we will see how we can apply a function to every row in a Pandas Dataframe. Apply Function to Every Row in a P
    7 min read
  • Joining two Pandas DataFrames using merge()
    The merge() function is designed to merge two DataFrames based on one or more columns with matching values. The basic idea is to identify columns that contain common data between the DataFrames and use them to align rows. Let's understand the process of joining two pandas DataFrames using merge(), e
    4 min read
  • Python | Pandas DataFrame.astype()
    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. DataFrame.astype() method is used to cast a pandas object to a specified dtype.astype(
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences