← Back to Pandas Course | Chapter 13: Performance & Best Practices | Lesson 1 of 6

Vectorization बनाम Loops

Vectorized operations तेज़ compiled code में चलते हैं, जबकि rows पर Python loops कहीं ज़्यादा धीमे होते हैं।

In this page:

  1. vectorization vs loops
Syntax
python
df["result"] = df["column"] * 2
df["result"] = np.where(condition, value1, value2)

vectorization vs loops

df["a"] * 2 या np.where जैसे whole-column operations Python loops के overhead से बचते हैं। iterrows और manual loops आमतौर पर 10 से 100 गुना धीमे होते हैं। पहले built-ins का उपयोग करें, फिर apply, और loops को आखिर में।

Note: अगर आप खुद को iterrows लिखते पाएं, तो vectorized alternative ढूंढें।

उदाहरण: vectorization vs loops

python
import numpy as np
import pandas as pd

df = pd.DataFrame({"a": range(1, 6)})
looped = [x * 2 for x in df["a"]]
vector = df["a"] * 2
df["size"] = np.where(df["a"] > 3, "big", "small")
print(looped == vector.tolist())
print(df)

# Output:
# True
#    a   size
# 0  1  small
# 1  2  small
# 2  3  small
# 3  4    big
# 4  5    big
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. calculations के लिए iterrows का उपयोग करना
  2. DataFrames को row by row बढ़ाना
  3. vectorized method होने पर भी apply का उपयोग करना
चैप्टर सारांश
  • पूरे columns को vectorize करें
  • Loops कहीं ज़्यादा धीमे हैं
  • np.where if/else की जगह लेता है
  • Loops को आखिरी उपाय के रूप में उपयोग करें
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.