Vectorization (Pandas)

Vectorization is applying an operation to a whole Series or DataFrame at once instead of looping row by row. pandas runs these operations in fast compiled C/NumPy code, making vectorized code far quicker than Python loops.

Pandas

Writing df['total'] = df['price'] * df['qty'] multiplies two entire columns in one optimized pass, with no visible loop. This is the idiomatic pandas style: think in terms of whole columns. The same applies to comparisons, string methods via .str, and date methods via .dt.

The payoff is speed and clarity. A Python for-loop or iterrows() over a large frame can be tens or hundreds of times slower than the equivalent vectorized expression, because each iteration pays Python's per-step overhead while a vectorized call pays it once.

When no vectorized operation fits, apply() is the readable fallback, though it still loops internally. The rule of thumb: prefer built-in vectorized operations, reach for apply only when necessary, and avoid explicit row loops almost always.

Syntax

df['c'] = df['a'] + df['b']  # operates on whole columns at once

Examples

Python

import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(df["a"] + df["b"])

Output:

0    11
1    22
2    33
dtype: int64

Learn it in a lesson

See also

Back to the Dictionary