Row iteration processes a tabular dataset one record at a time through sequential procedural evaluation. In pandas, it offers a familiar baseline for computing statistics, but can become a dominant performance bottleneck. section 7.2 section 7.6
Common pandas approaches form a practical performance ladder:
- Explicit indexing with iloc repeatedly retrieves each row and is generally slow. section 7.2.2
- iterrows simplifies the loop but remains inefficient because it still evaluates rows individually. section 7.2.2
- itertuples preserves the loop-based style while reducing the measured mean time to 18 seconds in the example. section 7.2.2
- apply processes each row through a function; dictionary-style access took 9.5 seconds, while attribute access took 14 seconds in the reported tests. section 7.2.2
- Vectorization replaces row-by-row evaluation with column operations and is the preferred direction when the computation permits it. section 7.2.2 section 7.6
Mean taxi-tip fraction
Load NYC trip records, then compute tip_amount divided by total_amount. A loop accumulates both columns, while the vectorized form evaluates df["tip_amount"] / df["total_amount"] and averages the resulting series. Benchmark competing approaches on sampled data rather than assuming a fixed ranking across pandas versions. section 7.2 section 7.2.2 section 7.6
