---
title: "Tech Tip #67: Stop looping over DataFrame rows"
description: "Looping over a DataFrame row by row wastes your processor."
url: https://greencode.ai/tech-tips/67-vectorise-dataframes/
---

# Tech Tip #67: Stop looping over DataFrame rows

**Looping over a DataFrame row by row wastes your processor.**

### The problem

Python loops over pandas rows (iterrows, apply with Python functions) run interpreted code for every row, when vectorised operations do the same job in optimised native code.

### The fix you can use today

- Use vectorised column operations instead of iterrows().
- Use built-in methods (groupby, merge, str accessors) before custom apply().
- Profile the notebook step that takes longest first.

### Tools that help

- [GreenCode Constitution skill](https://greencode-constitution.org/?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode) (GreenCode researchers): open-source energy principles and a catalogue of 37 energy anti-patterns that an AI coding agent can follow to find and fix waste like this
- [CodeCarbon](https://github.com/mlco2/codecarbon?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode): a Python package that estimates the energy and CO2 of a run from hardware power and regional grid intensity

### How GreenCode helps

GreenCode helps tackle this by building a load test from the system's own endpoints that records energy as well as speed and ranks the hotspots by energy, so you know which steps to fix first. [More on this](https://greencode.ai/feature/automated-performance-testing/).

### Tags

#python#loops#performance

### Sources

- [pandas documentation: Enhancing performance](https://pandas.pydata.org/docs/user_guide/enhancingperf.html?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode)
- [GreenCode Constitution skill, energy anti-patterns: R5 interpreted languages for CPU workloads](https://greencode-constitution.org/skill.md?utm_source=greencode.ai&utm_medium=referral&utm_campaign=greencode)

[All GreenCode Tech Tips](https://greencode.ai/tech-tips/)

#### Key Facts

- Tip **#67**
- For **Developers**
- Category **Code efficiency**
- Format **short video**
![GreenCode](https://greencode.ai/wp-content/uploads/2024/12/greencode-logo-website-small-colours-2.webp)

Want this checked on your own system? Talk to the GreenCode team.

[Get in touch](https://greencode.ai/contact/)
