The fastest and most efficient way to iterate over rows in a Pandas DataFrame is to avoid row-by-row loops completely and use vectorized operations (NumPy/Pandas built-in math). When you must loop, itertuples() is the fastest method.
Performance Comparison (Fastest to Slowest)
| Method | Speed | Best Use Case |
|---|---|---|
| Vectorization | Fastest (100x+) | Math, column operations, filtering |
df.itertuples() |
Fast | Looping when custom logic is required |
df.apply() |
Moderate | Complex row-wise functions |
df.iterrows() |
Slowest | Avoid on large datasets |
1. Vectorization (Recommended)
Vectorization operates on entire arrays in C under the hood instead of one Python row at a time.
python
import pandas as pd
df = pd.DataFrame({'price': [100, 200, 300], 'tax': [0.1, 0.2, 0.15]})
# Fast: Vectorized calculation
df['total'] = df['price'] * (1 + df['tax'])
2. Using itertuples() (When You Must Loop)
If you need conditional logic that cannot be vectorized, itertuples() yields lightweight namedtuples instead of heavy Pandas Series objects.
python
for row in df.itertuples(index=False):
if row.price > 150:
print(row.price, row.tax)
Key Takeaway
Always default to vectorization for data transformations, and fall back to itertuples() only when row-by-row iteration is unavoidable.
You must log in or register to comment.
