How to iterate over rows in a DataFrame in Pandas
• 1 minPandas 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]})
Loop over a specific column using a for loop
for firstname in df["firstname"]:
print(firstname)
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)
Loop over rows using iterrows()
for idx, row in df.iterrows():
print(f"{row['student']} : {row['gpa']}")