pandas iterrows
for index, row in df.iterrows(): gives you each row as a Series, so row["col"] reads a value. It works, but it is the slowest way to process a DataFrame. For calculations use whole-column operations such as df["a"] * df["b"]; when you really need a loop, itertuples is several times faster.
Syntax
for index, row in df.iterrows(): ... | for row in df.itertuples(index=True): ...Examples
import pandas as pd
df = pd.DataFrame({"item": ["pen", "ink"], "qty": [3, 2], "price": [1.5, 4.0]})
[f"{i}: {row['item']} x {row['qty']}" for i, row in df.iterrows()]Result: ['0: pen x 3', '1: ink x 2']
Each row arrives as (index label, Series).
[r.item + " costs " + str(r.qty * r.price) for r in df.itertuples()]Result: ['pen costs 4.5', 'ink costs 8.0']
itertuples gives named tuples: read fields as attributes. It is faster and keeps each column's type.
df["total"] = df["qty"] * df["price"]
dfResult:
item qty price total
0 pen 3 1.5 4.5
1 ink 2 4.0 8.0The same calculation with no loop at all. This is the pandas way.
df.to_dict("records")Result: [{'item': 'pen', 'qty': 3, 'price': 1.5, 'total': 4.5}, {'item': 'ink', 'qty': 2, 'price': 4.0, 'total': 8.0}]
A list of plain dicts, handy when you hand rows to other code such as an API call.
Try it yourself
Add a column monthly that holds each salary divided by 12, and return the columns name, salary and monthly, in that order, for every employee.
emp: 8 rows, first 4 shown
| emp_id | name | dept | salary | city | years |
|---|---|---|---|---|---|
| 1 | "Ava Chen" | "Sales" | 62000 | "Boston" | 3 |
| 2 | "Ben Ortiz" | "Engineering" | 98000 | "Austin" | 6 |
| 3 | "Cara Patel" | "Marketing" | 71000 | "Boston" | 4 |
| 4 | "Dev Singh" | "Engineering" | 105000 | "Denver" | 9 |
Free, no account needed. Real pandas runs in your browser; the first run takes a few seconds to load Python.
Common mistakes
- Changing row inside the loop: row is a copy, so row["qty"] = 0 does not change the DataFrame. Use df.at[index, "qty"] = 0, or better, a column operation.
- Types change: iterrows builds a Series per row, so a row mixing whole numbers and decimals turns the whole numbers into floats. itertuples does not.
- Looping to calculate a column: on a large table a loop can take minutes where a column expression takes milliseconds.
More practice: iterrows
These drills check your answer on live data, free, no account needed.
- Classify with applyWrite a function that labels an order "small" when qty is under 5, "medium" from 5 to 19, and "large" at 20 or more. Apply it to the `qty` column and return the labels as a Series.
Questions
What is the fastest way to loop over rows in pandas?
Avoid the loop with column operations. If a loop is unavoidable, itertuples is the fastest built-in; iterrows is the slowest.
How do I apply a function to each row?
df.apply(func, axis=1) passes each row to your function. It is tidier than a loop but still row by row.
How do I loop over columns?
for name, col in df.items(): gives each column name and its Series.
Related
- applyHow to use apply in pandas on a Series or DataFrame, with axis=1 for row-wise logic, lambdas, returning several columns, and why vectorized code is faster.
- mapHow Series.map works in pandas to recode a column with a dict or lookup Series, apply a function per value, what unmatched values become, and map vs replace.
- where, mask and np.whereHow to create a conditional column in pandas: np.where for if-else, np.select for several conditions, Series.where to keep values that pass a test, and mask.
- loc vs ilocThe difference between loc and iloc in pandas: loc selects by index label and column name, iloc by integer position. Slices, lists and boolean masks.
Interview and translation guides
- Timed mock interview
- pandas interview questions
- The pandas interview round
- SQL to pandas
- XLOOKUP in pandas
- pandas for Excel users
- groupby exercises