Row-wise processing
Read row values in a loop while retaining readable field access.
Pandas · Module
Iterate through DataFrame rows as namedtuples, optionally including the index and choosing a custom tuple type name. Set name=None for ordinary tuples.
Call itertuples() to obtain an iterator whose rows expose column values as tuple fields. By default each row is a namedtuple named Pandas and starts with the index; disable the index or provide a custom tuple name when needed.
DataFrame.itertuples(index=True, name='Pandas')| Name | Type | Description |
|---|---|---|
index | bool, default True | Whether to include the index as the first tuple element; defaults to True. |
name | str or None, default "Pandas" | The name assigned to returned namedtuples, or None for regular tuples; defaults to "Pandas". |
An iterator producing one namedtuple for each DataFrame row; the first field may be the index, followed by column values.
import pandas as pd
df = pd.DataFrame(
{"num_legs": [4, 2], "num_wings": [0, 2]},
index=["dog", "hawk"],
)
for row in df.itertuples(index=False, name="Animal"):
print(row.num_legs, row.num_wings)Iterates over rows without including the index and yields namedtuples called Animal.
Read row values in a loop while retaining readable field access.
Exclude the index when exporting or passing row values to another routine.
Use ordinary tuples for lightweight positional processing.
itertuples() returns an iterator that produces one namedtuple per DataFrame row. The index is included as the first field by default, followed by column values.
Follow-up: How would you produce ordinary tuples without the index? Use df.itertuples(index=False, name=None).
Set index=False to omit the index field. Set name=None to yield regular tuples instead of namedtuples.
Follow-up: What happens if name is a string? Each yielded namedtuple uses that string as its type name.
Column labels normally become namedtuple fields, but labels that are invalid Python identifiers, repeated, or begin with an underscore are renamed to positional names. Code requiring stable attribute names should account for that behavior.
Follow-up: Why might positional access be safer for arbitrary schemas? Column labels can be transformed, so positions avoid depending on generated field names.
DataFrame.iterrowsDataFrame.itemsDataFrame.__iter__