How to iterate over rows in a DataFrame in Pandas

1 min readPandasDataFrameGetting StartedLoop
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Pandas gives you the ability to loop over columns and rows.

Here are the different ways to loop over columns or rows using the Pandas Library.

We define our DataFrame first

We define an example DataFrame.

import pandas as pd
df = pd.DataFrame({"firstname":["Caroline", "Sebastian", "Bob", "John"],
                   "lastname":["Jones", "Smith", "Di Caprio", "Lennon"],
                   "gpa":[4.1233, 2.242, 4.152,  5.923]})
We first define our DataFrame

Loop over a specific column using a for loop

for firstname in df["firstname"]:
	print(firstname)
We loop over a column and print the values

Loop over rows using apply

We usually use apply when we want to create another column with the current Data frame data.

df["fullname"] = df.apply(lambda row: f'{row["firstname"]} {row["lastname"]}', axis=1)
We loop over the rows using apply and axis=1

Loop over rows using iterrows()

for idx, row in df.iterrows():
    print(f"{row['student']} : {row['gpa']}")
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.