×

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

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

How to Pass a list as an Argument in Python

Lists in Python A list is a datatype in python which is used to store the data in a sequence. The lists are mutable; that is, we can change the values...

3 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Python String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the string...

1 minute read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

os.stat() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

Python pynmea2

Define Pynmea2 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...

4 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

How to Install Numpy in PyCharm

What is PyCharm? JetBrains created the hybrid platform known as PyCharm as a Python IDE. The Python IDE PyCharm is used by some major companies, including Twitter, Facebook, Amazon, and many...

4 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Convert int to Float in Python using Pandas

Introduction We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float So let us create another Dataset on which...

2 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python and its advantages

What is Python? Python is an object-oriented programming language, a general-purpose programming language with a high level, and also an interpreted language that has an easy syntax and dynamic semantics. Python...

7 minutes read.

Writing to Excel using 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...

3 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.