• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Iterate Rows in a Pandas Dataframe

Iterate Rows in a Pandas Dataframe

Author: Aditya Raj
Last Updated: January 23, 2023

We use pandas dataframes to handle tabular data in python. In this article, we will discuss different ways to iterate rows in a pandas dataframe.

Table of Contents
  1. Iterate a Pandas Dataframe Using iloc Attribute
  2. Iterate Rows in a Pandas Dataframe Using the loc Attribute
  3. Iterate Rows Using iterrows() Method in Pandas
  4. Conclusion

Iterate a Pandas Dataframe Using iloc Attribute

The iloc attribute in a pandas dataframe is used to select a row at a specified position from the dataframe. The iloc attribute contains the  _iLocIndexer object. Using the _iLocIndexer object, we can select any row from the dataframe using the position of the row and python indexing. 

To iterate rows in the pandas dataframe using the iloc attribute, we will first find the number of rows in the dataframe using the len() function. The len() function takes the dataframe as its input and returns the number of rows. 

After finding the number of rows, we will use a for loop and _iLocIndexer object to iterate rows of the dataframe as shown below.

import pandas as pd
myDicts=[{"Roll":1,"Maths":100, "Physics":80, "Chemistry": 90},
        {"Roll":2,"Maths":80, "Physics":100, "Chemistry": 90},
        {"Roll":3,"Maths":90, "Physics":80, "Chemistry": 70}]
df=pd.DataFrame(myDicts)
print("The input dataframe is:")
print(df)
print("The rows are:")
num_rows=len(df)
for position in range(num_rows):
    print(df.iloc[position])

Output:

The input dataframe is:
   Roll  Maths  Physics  Chemistry
0     1    100       80         90
1     2     80      100         90
2     3     90       80         70
The rows are:
Roll           1
Maths        100
Physics       80
Chemistry     90
Name: 0, dtype: int64
Roll           2
Maths         80
Physics      100
Chemistry     90
Name: 1, dtype: int64
Roll          3
Maths        90
Physics      80
Chemistry    70
Name: 2, dtype: int64

In this example, we first converted a list of dictionaries to a dataframe. Then, we calculated the number of rows in the dataframe using the len() function. After this, we used a for loop and the iloc attribute to iterate over the dataframe.

Iterate Rows in a Pandas Dataframe Using the loc Attribute

The loc attribute in a pandas dataframe is used to select a row at a specified index from the dataframe. The loc attribute contains a _LocIndexer object. Using the _LocIndexer object, we can select any row in a dataframe using the index of the row and the indexing operator. 

To iterate through rows in the pandas dataframe using the loc attribute, we will first get the list containing the index values using the index attribute of the dataframe. Then, we will use a for loop and the loc attribute to iterate rows as shown in the following example.

import pandas as pd
myDicts=[{"Roll":1,"Maths":100, "Physics":80, "Chemistry": 90},
        {"Roll":2,"Maths":80, "Physics":100, "Chemistry": 90},
        {"Roll":3,"Maths":90, "Physics":80, "Chemistry": 70}]
df=pd.DataFrame(myDicts)
print("The input dataframe is:")
print(df)
df.set_index("Roll",inplace=True)
print("The rows are:")
indices=df.index
for index in indices:
    print(df.loc[index])

Output:

The input dataframe is:
   Roll  Maths  Physics  Chemistry
0     1    100       80         90
1     2     80      100         90
2     3     90       80         70
The rows are:
Maths        100
Physics       80
Chemistry     90
Name: 1, dtype: int64
Maths         80
Physics      100
Chemistry     90
Name: 2, dtype: int64
Maths        90
Physics      80
Chemistry    70
Name: 3, dtype: int64

In this example, we have used the loc and the index attribute of the dataframe to iterate through the rows.

The loc attribute can be helpful when we have to iterate through the rows of a dataframe at specific indices. You can select a list of indices and iterate over the rows having those indices using the loc operator without knowing the rows’ position in the dataframe. On the other hand, If you want to iterate through a dataframe using the iloc attribute, you need to know the position of the required rows in the dataframe.

Iterate Rows Using iterrows() Method in Pandas

Instead of using the iloc and loc attributes, you can use the iterrows() method to iterate through rows in a pandas dataframe. 

The iterrows() method, when invoked on a dataframe, returns an iterator object to the rows of the dataframe. After creating the iterator object, you can use a for loop to iterate through the rows of the pandas dataframe as shown below.

import pandas as pd
myDicts=[{"Roll":1,"Maths":100, "Physics":80, "Chemistry": 90},
        {"Roll":2,"Maths":80, "Physics":100, "Chemistry": 90},
        {"Roll":3,"Maths":90, "Physics":80, "Chemistry": 70}]
df=pd.DataFrame(myDicts)
print("The input dataframe is:")
print(df)
print("The rows are:")
for row in df.iterrows():
    print(row)

Output:

The input dataframe is:
   Roll  Maths  Physics  Chemistry
0     1    100       80         90
1     2     80      100         90
2     3     90       80         70
The rows are:
(0, Roll           1
Maths        100
Physics       80
Chemistry     90
Name: 0, dtype: int64)
(1, Roll           2
Maths         80
Physics      100
Chemistry     90
Name: 1, dtype: int64)
(2, Roll          3
Maths        90
Physics      80
Chemistry    70
Name: 2, dtype: int64)

Conclusion

In this article, we have discussed different ways to iterate through rows of a dataframe in python. 

To learn more about python programming, you can read this article on how to sort a pandas dataframe. You might also like this article on how to drop columns from a pandas dataframe.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us