vectorize() (NumPy)

np.vectorize() wraps an ordinary Python function so it can be called on whole arrays, applying it element by element and handling broadcasting. It is a convenience wrapper, not a true performance optimization.

NumPy

When you have a scalar Python function and want to apply it across an array without writing the loop yourself, np.vectorize gives it an array-friendly interface that also supports broadcasting between multiple array arguments. The result is cleaner-looking code.

The important caveat is in the docs themselves: vectorize is provided primarily for convenience, not speed. It still calls your Python function once per element under the hood, so it does not gain the C-loop speed of real vectorization. Treat it as a tidy loop, not a fast one.

Whenever the operation can be written with built-in ufuncs, arithmetic, or np.where, prefer those — they are genuinely vectorized. Reserve np.vectorize for logic that truly cannot be expressed with array operations.

Syntax

vfunc = np.vectorize(func); vfunc(array)

Examples

Python

import numpy as np
f = np.vectorize(lambda x: x * 2)
print(f(np.array([1, 2, 3])))

Output:

[2 4 6]

Learn it in a lesson

See also

Back to the Dictionary