×

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe

This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are rows and columns in the Data Frame of Pandas library in Python, and How can we iterate over the rows and columns in Pandas Data Frame.

What are Pandas in Python?

Pandas is a very widely used library in Python. It is an open-source, potent data analysis tool embedded into a library written in Python. The Pandas library leverages the power and the speed to its peak extent to make the data analysis and processing easier for Big Data domain people to make their jobs easier, mainly the Data Scientists. As a fact good to know since the Pandas can be visualized similar to Microsoft Excel sheet; Excel is written in Python too.

Understanding Python Pandas Data Structures

The Pandas library can be broadly distinguished mainly into two main sub-categories: Series and Data Frame models.

  1. Series Data Structure in Pandas: It is a one-dimensional array with an indexing feature. The Series Data Structure in Python stores a single column or only a single row of data in its Data Frame.
  2. Data Frame Data Structure in Pandas: It is usually represented in a tabular-like spreadsheet kind structure, which means rows which are each of which contains one or multiple columns to it.

A one-dimensional Array labelled is capable of holding any data series into it. A two-dimensional array is also labelled structure in nature with columns of potentially different data types in the Data Frame data structure in Pandas Python.

Iterating over the Rows and Columns in Pandas Data Frame

To iterate over a Data Frame in Pandas Python, we need to understand how can we iterate over a Dictionary in Python because we iterate over the keys in the dictionary in which each key consists of a particular value; the same methodology we follow to iterate over a Data Frame in Pandas library in Python.

Iterating over the elements in Pandas Data Frame is possible mainly in two ways, and they are

  1. Iterating over the rows.
  2. Iterating over the columns.

Iterating over the Rows

There are three in-built functions which will help us in iterating over the rows in Pandas Data Frame, which are iterrows(), itertuples(), and iteritems(); we will now see each function one by one

  1. Iterrows() Function

See the below code to understand the iterrows() function clearly.

Code:

#command for the importing pandas as pd
import pandas as pd
  
# dictionary of lists
dict_123 = {'name':["apsarasa", "pankaj tripathi", "sudhir babu", "Geeku ranjith"],
        'degree': ["B.tech", "LLB", "CA", "M.tech"],
        'score':[90, 40, 80, 98]}
 
# The Code to creating a dataframe from a dictionary
df_11 = pd.DataFrame(dict_123)
 
print(df_11)

Output:

        name                  degree          score
0       Apsarasa              B.tech          90
1       Pankaj Tripathi       LLB             40
2       Sudhir Babu           CA              80
3       Geeku ranjith         M.tech          98
  • Iteritems() Function

Code:

#Command for the importing pandas as pd
import pandas as pd
  
# dictionary of lists
dict_123 = {'name':["apsarasa", "pankaj tripathi", "sudhir babu", "Geeku ranjith"],
        'degree': ["B.tech", "LLB", "CA", "M.tech"],
        'score':[90, 40, 80, 98]}
 
# creating a dataframe from a dictionary
df_11 = pd.DataFrame(dict)
 
print(df_11)

Output

        name             degree          score
0       Apsarasa              B.tech       90
1       Pankaj Tripathi       LLB          40
2       Sudhir Babu           CA           80
3       Geeku ranjith         M.tech       98
  • Iteritems() Function

Code

#Command for importing pandas as pd
import pandas as pd
  
# dictionary of lists
dict_123 = {'name':["apsarasa", "pankaj tripathi", "sudhir babu", "Geeku ranjith"],
        'degree': ["B.tech", "LLB", "CA", "M.tech"],
        'score':[90, 40, 80, 98]}


# creating a dataframe from a dictionary
df_11 = pd.DataFrame(dict_123)
 
# using iteritems() function to retrieve rows
for key, value in df_11.iteritems():
    print(key, value)
    print()

Output

Name
 0           apsarasa
1    pankaj tripathi
2        sudhir babu
3      Geeku ranjith
Name: name, dtype: object






degree 
0    B.tech
1       LLB
2        CA
3    M.tech


Name: degree, dtype: object


Score
0	90
1    40
2    80
3    98
Name: score, dtype: int64 

Iterating over Columns

To iterate over the columns, we need to calculate the Data Frame columns; after that, we need to repeat to pull over the columns of the Data Frame.

See the code below to iterate over the columns in Data Frame Pandas Python

Code:

#Command for importing pandas as pd
import pandas as pd


# dictionary of lists
dict_123 = {'name':["apsarasa", "pankaj tripathi", "sudhir babu", "Geeku ranjith"],
        'degree': ["B.tech", "LLB", "CA", "M.tech"],
        'score':[90, 40, 80, 98]}




# creating a dataframe from a dictionary
df_11 = pd.DataFrame(dict_123)


print(df_11)

Output:

    name              degree       score
0   apsarasa          B.tech       90
1   pankaj tripathi   LLB          40
2   sudhir babu       CA           80
3   Geeku ranjith     M.tech       98

After getting the output we will now write a smaller code to iterate over the columns

Code:

df_11 = pd.DataFrame(dict_123)


#print(df_11)


columns = list(df_11)


for i in columns:


    print(df_11[i][2])

Output:

sudhir babu
CA
80

Related Topics

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Python getattr() function

Python getattr() function The getattr() function in Python returns the value of the named attribute for the given object. Syntax getattr(object, name[, default]) Parameter object: It is a required parameter which represents an object. name: This parameter represents the...

1 minute read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Python String splitlines() method

Python String splitlines() method The string.splitlines() method in Python splits the specified string and returns a list of the lines in the string, breaking at line boundaries.  Syntax splitlines([keepends]) Parameter keepends(optional): This parameter specifies if...

1 minute read.

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Anaconda python 3.7 download for windows 10 64-bit

Before installing Anaconda, you need to first know what Anaconda actually is. Anaconda is an IDE (Integrated development environment) platform used to code and executes python programs. Anaconda works both online...

3 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.