Label-based row inspection
You need to inspect or transform each row using column labels and the row's index.
Pandas · Module
Iterate over DataFrame rows as index-and-Series pairs. Each row is exposed as a Series, so its values may not retain the original column dtypes; itertuples() is generally faster and preserves types better.
Call iterrows() to obtain an iterator whose items contain a row's index label and the row data as a Series. Because each row is represented as a Series, values can be coerced to a common dtype; use itertuples() instead when preserving types and improving iteration speed matter.
DataFrame.iterrows()An iterator yielding pairs of the row index label (or a tuple of labels for a MultiIndex) and the row data as a Series.
itertuples() returns namedtuples containing the row values.itertuples() as generally faster than this method.import pandas as pd
df = pd.DataFrame({"name": ["Ada", "Grace"], "score": [10, 12]})
for index, row in df.iterrows():
print(index, row["name"], row["score"])
Iterate through rows while accessing each row by column label.
You need to inspect or transform each row using column labels and the row's index.
A small or moderate DataFrame requires straightforward row-wise logic and dtype coercion is acceptable.
You need to handle each record together with its index label.
DataFrame.iterrows() yield?Each iteration yields a two-item tuple: the row's index label and a Series containing that row's values. For a MultiIndex, the index item is a tuple of labels.
Follow-up: How would you iterate while retaining column dtypes? Use itertuples(), which yields namedtuples and is generally faster.
iterrows() preserve dtypes?No. The row Series can promote values to a shared dtype, so the original column dtypes are not necessarily retained in each row. This differs from DataFrame column-wise dtype preservation.
Follow-up: What behavior demonstrates this? An integer value in a row containing a floating-point value can be represented as a float in the yielded Series.
iterrows() be avoided?Use iterrows() when row-wise Series access is convenient and the performance and dtype limitations are acceptable. Avoid treating the yielded objects as guaranteed writable views of the DataFrame.
Follow-up: What is the preferred alternative for faster, type-consistent row iteration? Use itertuples().
DataFrame.itertuplesDataFrame.items