Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy vectorize: otypes, excluded and signature

How numpy.vectorize wraps a scalar function for arrays, why it is not faster, and how otypes, excluded and signature fix common errors.

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.

  1. Write the scalar function.
    def classify(x, cutoff):
        return "high" if x >= cutoff else "low"
  2. Wrap it.
    import numpy as np
    vclassify = np.vectorize(classify)
  3. Call it on an array. The scalar cutoff is broadcast against the array.
    readings = [3.1, 7.8, 5.0]
    result = vclassify(readings, 5.0)
    print(result.tolist())      # ['low', 'high', 'high']
  4. State the output type when you know it. Add otypes so NumPy does not have to infer it (see the troubleshooting section for why this matters).
    vclassify = np.vectorize(classify, otypes=[str])
  5. Use it as a decorator if you prefer. The manual shows both forms: @np.vectorize and @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

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.

numpy.vectorize parameters: defaults and effects (NumPy 2.5 manual)
ParameterDefaultAccepted valuesDocumented effect
pyfuncnp._NoValuePython callableFunction to vectorize; if omitted, vectorize returns a decorator
otypesNoneString of type characters or list of dtypes, one per outputSets output dtype so the function is not called on the first element to infer it
docNoneStringDocstring of the vectorized function; defaults to pyfunc.__doc__
excludedNoneSet of strings (names) or integers (positions)Arguments that are passed through and not vectorized; lowers performance
cacheFalseBooleanIf True and neither otypes nor signature is given, caches the first call to avoid the double call; wraps the function and slows later calls
signatureNoneGeneralized-ufunc string such as (m,n),(n)->(m)Lets the function take and return arrays instead of scalars

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about NumPy vectorize: otypes, excluded and signature

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →