Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python
communitycreator

What is Pandas DataFrame.iterrows() in Python?

AKASH BAJWA

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

Pandas.DataFrame is a two-dimensional data structure that stores different types of data. The DataFrame class in Pandas manipulates data as rows and columns.

This DataFrame.iterrows() method iterates through Pandas DataFrame rows as (index, Series) pairs. The iterator returns a tuple of column names and data in the form of a series.

Syntax


DataFrame.iterrows()
iterrows()

Parameter

This method does not take any argument value.

Return value

iter: This is an iterator that iterates over the rows of the frame, and returns each row as a tuple.

Example

In the code snippet below, we have a DataFrame that contains four observations: "Employee name," "Age," "Salary," and "Join Date."

import pandas as pd
# Creating a DataFrame with a column name
data = [["Alizy", 23, 8900, 2020], ["Montizo", 34, 6000, 2017],
["Zahafi", 45, 6570, 2021], ["Samreen", 55, 13000, 2022]]
df = pd.DataFrame(data, columns=[
'Name', 'Age', 'Salary', 'Join Date'])
# Iterating over the DataFrame rows
# Using df.iterrows()
for x in df.iterrows():
print(x)
print()
iterrows() implementation

Explanation

  • Lines 3–4: We create a nested list of employees having a name, age, salary, and company joining date.
  • Line 5–6: We convert the above-created nested list into a Pandas DataFrame by using data and column names as arguments to DataFrame().
  • Line 9: We iterate through each row of the above created DataFrame df and print each observation as a tuple. We use iterrows() to get each observation as a tuple.

RELATED TAGS

pandas
python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring