Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
numpy.vectorize wraps an ordinary Python function that handles one scalar at a time so that it accepts arrays and returns an array. You call vfunc = np.vectorize(myfunc) and then vfunc(array). The NumPy manual is explicit about what it does not do: it is provided primarily for convenience, not for performance, and the implementation is essentially a for loop. Use it when your function contains logic (such as an if statement) that cannot be written as plain array arithmetic, and use native array expressions when it can.
What numpy.vectorize is used for in research
Analysts often have a small rule written for one value: classify a measurement against a cutoff, apply a recoding scheme, or call a helper that takes scalars. Rewriting that rule as array arithmetic is not always practical. np.vectorize turns the scalar function into one that evaluates over successive tuples of the input arrays, like Python’s map, and it follows NumPy broadcasting rules for how the inputs are matched (NumPy v2.5 manual, numpy.vectorize). It returns a vectorized function when you pass a function, or a decorator when you do not.
Vectorize versus vectorized operations
The two phrases are easy to confuse. The NumPy broadcasting guide describes broadcasting as “a means of vectorizing array operations so that looping occurs in C instead of Python.” That is true vectorization: the loop runs in compiled code. np.vectorize shares the name and the convenient calling style, but the loop still runs in Python. The data table below lists the parameters you can use to control it.
NumPy vectors and NumPy vector inputs
People searching for “numpy vector” or “numpy vectors” usually mean a one-dimensional ndarray, for example np.array([3.1, 7.8, 5.0]). NumPy has no separate vector class; a vector is simply an array with one axis. np.vectorize accepts such arrays, higher-dimensional arrays, lists and scalars. Arguments are combined by broadcasting, so a scalar or a shorter axis can pair with a longer one.
How to install or access it
NumPy’s install page (numpy.org/install, read 2026-11-13) gives these routes. With pip:
pip install numpy
In an isolated virtual environment:
python -m venv my-env
source my-env/bin/activate # macOS and Linux
my-envScriptsactivate # Windows
pip install numpy
With conda (defaults or conda-forge channel):
conda create -n my-env
conda activate my-env
conda install numpy
Then import it in your script as import numpy as np. No separate installation is needed for np.vectorize; it ships with NumPy.
Step-by-step: vectorize a scalar function
The signature in the NumPy v2.5 manual is numpy.vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None, cache=False, signature=None). The steps below use a small classification rule as an illustrative example on assay readings. The outputs shown were produced by running the code on NumPy 2.5.4.
- Write the scalar function.
def classify(x, cutoff): return "high" if x >= cutoff else "low" - Wrap it.
import numpy as np vclassify = np.vectorize(classify) - Call it on an array. The scalar
cutoffis broadcast against the array.readings = [3.1, 7.8, 5.0] result = vclassify(readings, 5.0) print(result.tolist()) # ['low', 'high', 'high'] - State the output type when you know it. Add
otypesso NumPy does not have to infer it (see the troubleshooting section for why this matters).vclassify = np.vectorize(classify, otypes=[str]) - Use it as a decorator if you prefer. The manual shows both forms:
@np.vectorizeand@np.vectorize(otypes=[float]).
The manual’s own example
The manual defines myfunc(a, b) to return a - b if a > b, otherwise a + b, then calls np.vectorize(myfunc)([1, 2, 3, 4], 2), which returns array([3, 4, 1, 2]). The same call with otypes=[float] returns floating-point values: the manual shows the element type changing from numpy.int64 to numpy.float64.
Output and how to read it
The result is a NumPy array whose shape follows broadcasting of the inputs. With one array argument the output has the same shape. With two arguments of different shapes the output has the broadcast shape. In a run on NumPy 2.5.4, myfunc applied to a column [[1], [2]] and a row [1, 2, 3] returned array([[2, 3, 4], [1, 4, 5]]), a 2 x 3 result.
The output dtype is decided before your data are processed in bulk. The manual states that if neither otypes nor signature is given, the function is called on the first element to determine the number of outputs and their dtype. That single decision then applies to every element.
Vectorize, native expressions and frompyfunc compared
| Approach | Where the loop runs | Output dtype | Use when |
|---|---|---|---|
np.vectorize(pyfunc) |
Python (the manual: “essentially a for loop”) | Inferred from the first element, or set by otypes |
The logic is scalar-only and convenience matters more than speed |
| Native array expressions and ufuncs with broadcasting | C (broadcasting guide) | Follows NumPy type rules for the operation | The rule can be written with array operations |
np.frompyfunc(func, nin, nout) |
Python function called per element; returns a ufunc | Always object |
You need a ufunc and accept object arrays |
Troubleshooting
Results are truncated to integers
Because the dtype comes from the first call, a function that returns an integer for the first element and a decimal later will be cast to integers. Run on NumPy 2.5.4, a function returning 1 for positive input and 2.5 otherwise gave array([1, 2, 2]) for inputs [1, -1, -2], whereas adding otypes=[float] gave array([1. , 2.5, 2.5]). Fix: pass otypes.
The function seems to run one extra time
That is the first-element call. In a counting test on NumPy 2.5.4, vectorizing a function over three elements called it four times without otypes and three times with otypes=[float]. The manual describes cache=True as a way to avoid the double call, but it also says caching wraps the function and slows later calls, so it is meant only for expensive functions. For a function with side effects, such as writing to a file, set otypes so it is not invoked an extra time.
An argument should not be vectorized
Use excluded, a set of argument names (strings) or positions (integers) that are passed through unchanged. The manual’s example excludes the coefficient list of a polynomial: excluded={0, 'p'} lets vpolyval([1, 2, 3], x=[0, 1]) return array([3, 6]). The manual also notes that using the keyword interface and excluded reduces performance further. In a run on NumPy 2.5.4, np.vectorize(myfunc, excluded={'y'})([1, 2, 3], y=2) returned array([3, 4, 1]).
The function takes arrays, not scalars
By default the function is assumed to take and return scalars. If it operates on whole vectors or matrices, give signature in generalized-ufunc notation, such as '(m,n),(n)->(m)'. The manual’s example is np.vectorize(np.convolve, signature='(n),(m)->(k)'); applied to np.eye(4) and [1, 2, 1], it returns a 4 x 6 array whose rows are shifted copies of [1, 2, 1].
ValueError: operands could not be broadcast together
Shapes are compared from the trailing dimension leftward and are compatible when equal or when one is 1, per the broadcasting guide. Mismatched shapes raise the error. Passing arrays of length 3 and 2 to a vectorized two-argument function raised ValueError: operands could not be broadcast together with shapes (3,) (2,) on NumPy 2.5.4. Reshape one input, for example to a column, or trim to matching lengths.
Memory use with large broadcasts
The broadcasting guide warns that broadcasting can use unnecessarily large memory, and in that case it is better to write the algorithm’s outer loop in Python. Related CASRAI guides on array building blocks include NumPy asarray, NumPy indices, NumPy roll and NumPy sum.
Free alternatives
All options below are part of NumPy itself, so they need no additional software.
| Alternative | What it gives you | Source |
|---|---|---|
| Native array expressions and ufuncs | Looping occurs in C; the route the broadcasting guide describes as vectorizing array operations | NumPy broadcasting guide |
numpy.frompyfunc |
A ufunc built from a Python function; output is always object dtype. Example: np.frompyfunc(oct, 1, 1)(np.array((10, 30, 100))) returns array(['0o12', '0o36', '0o144'], dtype=object) |
NumPy manual, numpy.frompyfunc |
np.vectorize with otypes or signature |
Convenience with explicit output typing and no first-element probe | NumPy manual, numpy.vectorize |
FAQ
Does np.vectorize make my code faster?
No. The manual states it is provided primarily for convenience, not for performance, and that the implementation is essentially a for loop. For speed, express the computation with array operations so the loop runs in C.
What is a NumPy vector?
A one-dimensional ndarray. NumPy does not define a separate vector type.
What do I pass to otypes?
A string of type characters or a list of dtypes, one per output, for example otypes=[float].
Can np.vectorize be used as a decorator?
Yes. The manual shows @np.vectorize and @np.vectorize(otypes=[float]).
How is it different from frompyfunc?
frompyfunc returns a ufunc and always produces object-dtype output, while vectorize lets you set output dtypes with otypes.
Sources
- NumPy v2.5 manual, numpy.vectorize (read 2026-11-13)
- NumPy user guide, Broadcasting (read 2026-11-13)
- NumPy v2.5 manual, numpy.frompyfunc (read 2026-11-13)
- NumPy installation (read 2026-11-13)
- Code outputs marked as run on NumPy 2.5.4 were produced by the CASRAI editors on 2026-11-13.
Data: numpy.vectorize parameters: defaults and effects (NumPy 2.5 manual)
Each parameter of numpy.vectorize with its default value and documented effect, compiled from the NumPy v2.5 reference manual entry and checked against the signature line.
| Parameter | Default | Accepted values | Documented effect |
|---|---|---|---|
| pyfunc | np._NoValue | Python callable | Function to vectorize; if omitted, vectorize returns a decorator |
| otypes | None | String of type characters or list of dtypes, one per output | Sets output dtype so the function is not called on the first element to infer it |
| doc | None | String | Docstring of the vectorized function; defaults to pyfunc.__doc__ |
| excluded | None | Set of strings (names) or integers (positions) | Arguments that are passed through and not vectorized; lowers performance |
| cache | False | Boolean | If True and neither otypes nor signature is given, caches the first call to avoid the double call; wraps the function and slows later calls |
| signature | None | Generalized-ufunc string such as (m,n),(n)->(m) | Lets the function take and return arrays instead of scalars |
Sources
- NumPy v2.5 manual: numpy.vectorize (accessed 2026-11-13)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







