Universal Functions (ufuncs)
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page targets NumPy 2.5 (2.5.4 was the current release), and was checked in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. Every example was run on NumPy 2.5.4. NumPy 2.6 is under development and nothing here depends on it.
A universal function, or ufunc, is a function that operates on arrays element by element, supports broadcasting, type casting and several other standard features, and is implemented as compiled loops. np.add, np.sqrt, np.maximum, np.isnan and np.matmul are all instances of the single class numpy.ufunc. The operators +, -, *, /, **, %, == and < on arrays are thin wrappers that call the matching ufunc (np.add, np.subtract, np.multiply, np.true_divide, np.power, np.remainder, np.equal, np.less). Understanding ufuncs explains most of NumPy’s speed and most of its surprises. The shape rules that every ufunc applies to its inputs are on Broadcasting, and the dtype rules that pick the loop are on Type Promotion.
What makes a function a ufunc
A ufunc is an object, not a Python function, and it carries metadata that you can inspect.
import numpy as np
a = np.array([1.0, 4.0, 9.0])
print(np.sqrt(a)) # [1. 2. 3.]
print(type(np.sqrt)) # <class 'numpy.ufunc'>
print(np.sqrt.nin, np.sqrt.nout) # 1 1 (inputs, outputs)
print(np.add.nin, np.add.nargs) # 2 3 (nargs counts the output too)
print(np.add.types[:6]) # ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i']
print(np.sqrt.signature) # None (element-wise ufunc)
print(np.matmul.signature) # (n?,k),(k,m?)->(n?,m?)
print(np.vecdot.signature) # (n),(n)->()
ufunc.types lists the compiled loops as inputs->outputs character codes (??->? is boolean, bb->b is int8). When you call a ufunc, NumPy looks at the dtypes of the inputs, picks the first loop that every input can be safely cast to (see Type Promotion), casts in small buffered chunks and runs the inner loop. A signature of None means the ufunc is element-wise. A non-None signature, such as (n),(n)->(), marks a generalised ufunc (gufunc), described below.
Ufuncs fall into groups that are worth recognising by name.
| Group | Examples |
|---|---|
Arithmetic |
|
Exponents and logarithms |
|
Trigonometry and hyperbolics |
|
Comparison and logic |
|
Floating-point helpers |
|
Bit and integer |
|
Generalised |
|
np.divmod is a ufunc with two outputs (np.divmod(np.array([7, -7]), 2) returns (array([ 3, -4]), array([1, 1]))), and np.frexp also returns two arrays. np.fmax and np.fmin ignore NaN while np.maximum and np.minimum propagate it, a difference that matters in reductions. np.bitwise_count (population count) is available since NumPy 2.0.
Keyword arguments common to every ufunc
All ufuncs accept the same optional keywords. The most useful are out, where, dtype, casting, order and, for gufuncs, axes, axis and keepdims.
out: write into an existing array
out= places the result in an array you already own, avoiding a temporary allocation. The ufunc returns that same object.
import numpy as np
a = np.array([1.0, 4.0, 9.0])
out = np.empty(3)
r = np.multiply(a, 2, out=out)
print(r is out, out) # True [ 2. 8. 18.]
The output array must be broadcast-compatible with the result, and its dtype must be reachable under the casting rule. out may alias an input (np.add(a, 1, out=a) is the same operation as a += 1), and NumPy detects overlapping memory between inputs and outputs and makes a temporary copy when needed, so overlapping slices give the same answer as if no overlap existed.
where: compute only some elements
where= takes a boolean array (broadcast against the output) and computes the result only where it is true. Elements where it is false are left as they were in out.
import numpy as np
import warnings
x = np.array([1.0, -1.0, 4.0, -9.0])
res = np.full(4, np.nan)
np.sqrt(x, out=res, where=x >= 0)
print(res) # [ 1. nan 2. nan]
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
y = np.sqrt(x, where=x >= 0) # no out=: uninitialised memory in the masked slots
print(w[0].category.__name__, w[0].message)
Output:
[ 1. nan 2. nan]
UserWarning 'where' used without 'out', expect uninitialized memory in output. If this is intentional, use out=None.
Source: numpy.sqrt and NumPy 2.4.0 release notes
Without out=, NumPy allocates the result with np.empty, so the positions where where is false contain whatever was in that memory. Since NumPy 2.4 this case emits a UserWarning; older code, and most older tutorials, silently returned garbage there. Always pass out= with a sensible fill (np.zeros, np.full(..., np.nan), or a copy of the input) when you use where=. Pass out=None explicitly only if you really want the uninitialised result and accept the warning being silenced.
where= also suppresses floating-point errors for the masked-out elements, which makes it the clean way to avoid a division by zero instead of fixing the result afterwards:
import numpy as np
num = np.array([1.0, 2.0, 3.0])
den = np.array([2.0, 0.0, 4.0])
ratio = np.divide(num, den, out=np.zeros_like(num), where=den != 0)
print(ratio) # [0.5 0. 0.75]
Source: numpy.divide
dtype and casting: control the loop and the safety rule
dtype= selects the loop (and so the precision of the calculation and of the result). casting= states how permissive NumPy is when it must convert inputs or the output. The rules are no, equiv, safe, same_kind (the default) and unsafe.
import numpy as np
i = np.array([1, 2, 3])
try:
np.add(i, 1.5, out=np.zeros(3, dtype=int))
except Exception as e:
print(type(e).__name__, e)
# UFuncTypeError Cannot cast ufunc 'add' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
print(np.add(i, 1.5, out=np.zeros(3, dtype=int), casting="unsafe")) # [2 3 4]
small = np.array([1, 2, 3], dtype=np.int8)
print(np.add(small, small, dtype=np.float32).dtype) # float32
Source: NumPy reference: Casting rules
The default same_kind allows float64 to float32 but refuses float to int. This is why a += 1.5 on an integer array raises while a = a + 1.5 works: the in-place form has to fit the result into the existing integer array. NumPy 2.4 added a further rule, casting="same_value", which allows a conversion only when every value is represented exactly; see Data Types. Plain unsafe truncates silently, so use it deliberately.
order, subok, axes, axis and keepdims
-
order=sets the memory layout of the result (Kkeeps the input’s layout, the default). -
subok=Falsereturns a basendarrayinstead of a subclass. -
axes=,axis=andkeepdims=apply to generalised ufuncs, andaxis=andkeepdims=also apply to thereducefamily below.axesis a list of tuples that says which dimensions of each operand are the core dimensions; see the gufunc section.
Ufunc methods
Every binary ufunc has methods that generalise the same loop to whole arrays. These are the most powerful and the least known part of the API. The named reductions (np.sum, np.prod, np.max, np.cumsum, np.any and so on) are thin wrappers over reduce and accumulate; they are covered, with axis semantics, on Reductions and Axis Semantics.
import numpy as np
v = np.array([1, 2, 3, 4])
print(np.add.reduce(v)) # 10
print(np.add.accumulate(v)) # [ 1 3 6 10]
print(np.multiply.accumulate(v)) # [ 1 2 6 24]
print(np.add.reduceat(np.arange(8), [0, 4, 1, 5])) # [ 6 4 10 18]
print(np.multiply.outer(np.arange(1, 4), np.arange(1, 4)))
# [[1 2 3]
# [2 4 6]
# [3 6 9]]
print(np.subtract.outer([10, 20], [1, 2, 3]))
# [[ 9 8 7]
# [19 18 17]]
| Method | What it does |
|---|---|
|
Applies the operation along an axis until one value is left, so |
|
The running version of |
|
Reduces over slices that start at each index and end at the next one (or the end). If an index is not smaller than the next, only the element at that index is used, which is why |
|
Applies the operation to every pair, with output shape |
|
Unbuffered in-place operation at the given indices, so repeated indices accumulate. |
Note the default axis=0 for reduce and accumulate, which differs from np.sum, where axis=None flattens the whole array. A reduction with a ufunc that has no identity (np.maximum) fails on an empty input unless you supply initial=:
import numpy as np
print(np.maximum.reduce(np.array([], dtype=float), initial=-np.inf)) # -inf
m = np.arange(6).reshape(2, 3)
print(np.add.reduce(m, axis=1, keepdims=True))
# [[ 3]
# [12]]
print(np.add.reduce(m, where=m > 1, axis=1)) # [ 2 12]
Source: numpy.ufunc.reduce
ufunc.at and repeated indices
Fancy-index assignment evaluates a[idx] += 1 as "read the elements, add 1, write them back", so an index that appears twice is written twice with the same value and the increment happens once. ufunc.at runs the operation unbuffered, one index at a time, and accumulates correctly.
import numpy as np
b = np.zeros(5, dtype=int)
b[[0, 0, 1]] += 1
print(b) # [1 1 0 0 0] index 0 counted once
b = np.zeros(5, dtype=int)
np.add.at(b, [0, 0, 1], 1)
print(b) # [2 1 0 0 0]
print(np.bincount([0, 0, 1], minlength=5)) # [2 1 0 0 0] faster for plain counting
Source: numpy.ufunc.at
ufunc.at is correct but is the slow path unless NumPy has a fast implementation for the operation and dtype. For counting, np.bincount or np.add.reduceat over sorted data are usually much faster. The indexing side of this pitfall is on Advanced and Boolean Indexing.
Generalised ufuncs
A generalised ufunc works on sub-arrays (core dimensions) instead of scalars and loops over the remaining "loop" dimensions with broadcasting. The signature says which are which: (n),(n)->() means two vectors of the same length n are reduced to a scalar. np.matmul (the @ operator), np.vecdot, np.matvec and np.vecmat are gufuncs, so they broadcast over leading dimensions and take axes=.
import numpy as np
A = np.arange(24).reshape(2, 3, 4)
B = np.arange(8).reshape(4, 2)
print(np.matmul(A, B).shape) # (2, 3, 2) B is broadcast over the leading axis
x = np.ones((2, 3))
y = np.arange(6.0).reshape(2, 3)
print(np.vecdot(x, y)) # [ 3. 12.] dot product along the last axis
Source: numpy.vecdot and numpy.matmul
np.vecdot (NumPy 2.0) conjugates the first argument for complex data, as the mathematical definition requires, unlike np.dot. np.matvec and np.vecmat were added in NumPy 2.2. The complete treatment of these functions, and of np.linalg, is on Linear Algebra.
Choosing the right tool
Python-level wrappers: vectorize and frompyfunc
np.vectorize and np.frompyfunc turn an ordinary Python function into something that accepts arrays and broadcasts. Neither makes the function fast: the Python function is still called once per element.
import numpy as np
add = np.frompyfunc(lambda a, b: a + b, 2, 1)
r = add(np.arange(3), 10)
print(r, r.dtype) # [10 11 12] object
vmax = np.vectorize(lambda a, b: a if a > b else b)
print(vmax(np.array([1, 5, 3]), 2)) # [2 5 3]
Source: numpy.frompyfunc and numpy.vectorize
np.frompyfunc is a real numpy.ufunc (so it has .reduce, .accumulate and so on) but always returns object arrays. np.vectorize is a convenience class that infers the output dtype from the first element, which can go wrong; pass otypes= to fix it, and prefer a real ufunc composition when one exists. The first call of np.vectorize evaluates the function once more to find the output type unless otypes is given.
Scalars and ufuncs
A ufunc applied to NumPy or Python scalars returns a NumPy scalar, not a 0-d array: type(np.add(1, 2)) is numpy.int64 and type(np.add(1, 2.0)) is numpy.float64. NumPy scalars follow the NEP 50 promotion rules in which Python numbers are "weak" and NumPy scalars are "strong"; see Type Promotion. Scalar integer overflow warns while array overflow does not, as shown on Floating-Point Errors and errstate.
Extending ufuncs to your own types
Any class can take part in ufunc calls by defining __array_ufunc__. When a ufunc sees an argument with this method, NumPy calls it instead of running its own loop, which is how subclasses, Dask arrays and unit libraries intercept np.add(obj, 1) and np.sqrt(obj). The protocol, the related __array_function__ and the buffer and DLPack protocols are on Interoperability. Writing a new compiled ufunc is a C-API task; see C-API, Cython and F2PY.
Pitfalls summary
-
A
where=mask withoutout=leaves uninitialised data in the masked positions (a warning since NumPy 2.4). -
a[idx] += 1does not accumulate for repeated indices; usenp.add.atornp.bincount. -
a += 1.5fails on integer arrays because ofsame_kindcasting;a = a + 1.5creates a float array. -
reduceandaccumulatedefault toaxis=0;np.sumand friends default toaxis=None. -
np.maximum.reduceon an empty array raises unlessinitial=is given. -
np.vectorizeandnp.frompyfuncare loops in disguise. -
np.fmaxandnp.maximumdiffer on NaN.