
🐼 If you use for i in range(len(df)): in Pandas, you’re doing the compiler’s job by hand. There’s a better way.
When you start with Pandas, loops feel natural. They work. The problem is they don’t scale.
# ❌ Beginner approach
for i in range(len(df)):
if df.loc[i, "sales"] > 1000:
df.loc[i, "tier"] = "high"
else:
df.loc[i, "tier"] = "low"With 5 rows it seems fine. With 50,000 rows it becomes unacceptably slow.
Why? Pandas is processing a tiny operation per row, instead of handling the entire column at once with vectorized operations.
The solution: Boolean Indexing
# ✅ Vectorized approach
df["tier"] = "low"
df.loc[df["sales"] > 1000, "tier"] = "high"Same result. Drastically faster. More readable.
The key mental shift: Pandas was designed to think in columns, not rows. Once you make that switch, code gets shorter, execution gets faster, and Pandas finally feels like your ally.
💡 Explanation in a nutshell#
Loops in Pandas are the symptom of thinking “row by row” in a tool designed to think “column by column”. Boolean indexing, .apply() when you need complex logic, and native vectorized operations are the alternatives that give you 10x-100x more performance with less code.
More information at the link 👇

