Tsallaka zuwa abun ciki
Justice Tech School

Iterate Over Rows

Looping over rows is slow. When you must, use itertuples. Prefer vectorized operations.

Example
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['Ada', 'Bob', 'Cy', 'Di'], 'age': [30, 25, 35, 28], 'city': ['Lagos', 'Accra', 'Lagos', 'Nairobi'], 'score': [88.5, 92.0, 79.5, 85.0]})
for row in df.itertuples():
    print(row.name, row.age)
print(df['age'].sum())

Result

Ada 30
Bob 25
Cy 35
Di 28
118

Exercise

Loop over rows.

df.()

Quiz Test

Which is faster?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.