Universal functions (ufunc
)#
See also
A universal function (or ufunc for short) is a function that
operates on ndarrays
in an elementbyelement fashion,
supporting array broadcasting, type
casting, and several other standard features. That
is, a ufunc is a “vectorized” wrapper for a function
that takes a fixed number of specific inputs and produces a fixed number of
specific outputs. For detailed information on universal functions, see
Universal functions (ufunc) basics.
ufunc
#
Functions that operate element by element on whole arrays. 
Optional keyword arguments#
All ufuncs take optional keyword arguments. Most of these represent advanced usage and will not typically be used.
out
New in version 1.6.
The first output can be provided as either a positional or a keyword parameter. Keyword ‘out’ arguments are incompatible with positional ones.
New in version 1.10.
The ‘out’ keyword argument is expected to be a tuple with one entry per output (which can be None for arrays to be allocated by the ufunc). For ufuncs with a single output, passing a single array (instead of a tuple holding a single array) is also valid.
Passing a single array in the ‘out’ keyword argument to a ufunc with multiple outputs is deprecated, and will raise a warning in numpy 1.10, and an error in a future release.
If ‘out’ is None (the default), a uninitialized return array is created. The output array is then filled with the results of the ufunc in the places that the broadcast ‘where’ is True. If ‘where’ is the scalar True (the default), then this corresponds to the entire output being filled. Note that outputs not explicitly filled are left with their uninitialized values.
New in version 1.13.
Operations where ufunc input and output operands have memory overlap are
defined to be the same as for equivalent operations where there
is no memory overlap. Operations affected make temporary copies
as needed to eliminate data dependency. As detecting these cases
is computationally expensive, a heuristic is used, which may in rare
cases result in needless temporary copies. For operations where the
data dependency is simple enough for the heuristic to analyze,
temporary copies will not be made even if the arrays overlap, if it
can be deduced copies are not necessary. As an example,
np.add(a, b, out=a)
will not involve copies.
where
New in version 1.7.
Accepts a boolean array which is broadcast together with the operands. Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone. This argument cannot be used for generalized ufuncs as those take nonscalar input.
Note that if an uninitialized return array is created, values of False will leave those values uninitialized.
axes
New in version 1.15.
A list of tuples with indices of axes a generalized ufunc should operate
on. For instance, for a signature of (i,j),(j,k)>(i,k)
appropriate
for matrix multiplication, the base elements are twodimensional matrices
and these are taken to be stored in the two last axes of each argument.
The corresponding axes keyword would be [(2, 1), (2, 1), (2, 1)]
.
For simplicity, for generalized ufuncs that operate on 1dimensional arrays
(vectors), a single integer is accepted instead of a singleelement tuple,
and for generalized ufuncs for which all outputs are scalars, the output
tuples can be omitted.
axis
New in version 1.15.
A single axis over which a generalized ufunc should operate. This is a
shortcut for ufuncs that operate over a single, shared core dimension,
equivalent to passing in axes
with entries of (axis,)
for each
singlecoredimension argument and ()
for all others. For instance,
for a signature (i),(i)>()
, it is equivalent to passing in
axes=[(axis,), (axis,), ()]
.
keepdims
New in version 1.15.
If this is set to True, axes which are reduced over will be left in the
result as a dimension with size one, so that the result will broadcast
correctly against the inputs. This option can only be used for generalized
ufuncs that operate on inputs that all have the same number of core
dimensions and with outputs that have no core dimensions, i.e., with
signatures like (i),(i)>()
or (m,m)>()
. If used, the location of
the dimensions in the output can be controlled with axes
and axis
.
casting
New in version 1.6.
May be ‘no’, ‘equiv’, ‘safe’, ‘same_kind’, or ‘unsafe’.
See can_cast
for explanations of the parameter values.
Provides a policy for what kind of casting is permitted. For compatibility with previous versions of NumPy, this defaults to ‘unsafe’ for numpy < 1.7. In numpy 1.7 a transition to ‘same_kind’ was begun where ufuncs produce a DeprecationWarning for calls which are allowed under the ‘unsafe’ rules, but not under the ‘same_kind’ rules. From numpy 1.10 and onwards, the default is ‘same_kind’.
order
New in version 1.6.
Specifies the calculation iteration order/memory layout of the output array. Defaults to ‘K’. ‘C’ means the output should be Ccontiguous, ‘F’ means Fcontiguous, ‘A’ means Fcontiguous if the inputs are Fcontiguous and not also not Ccontiguous, Ccontiguous otherwise, and ‘K’ means to match the element ordering of the inputs as closely as possible.
dtype
New in version 1.6.
Overrides the DType of the output arrays the same way as the signature. This should ensure a matching precision of the calculation. The exact calculation DTypes chosen may depend on the ufunc and the inputs may be cast to this DType to perform the calculation.
subok
New in version 1.6.
Defaults to true. If set to false, the output will always be a strict array, not a subtype.
signature
Either a Dtype, a tuple of DTypes, or a special signature string indicating the input and output types of a ufunc.
This argument allows the user to specify exact DTypes to be used for the
calculation. Casting will be used as necessary. The actual DType of the
input arrays is not considered unless signature
is None
for
that array.
When all DTypes are fixed, a specific loop is chosen or an error raised
if no matching loop exists.
If some DTypes are not specified and left None
, the behaviour may
depend on the ufunc.
At this time, a list of available signatures is provided by the types
attribute of the ufunc. (This list may be missing DTypes not defined
by NumPy.)
The signature
only specifies the DType class/type. For example, it
can specify that the operation should be datetime64
or float64
operation. It does not specify the datetime64
timeunit or the
float64
byteorder.
For backwards compatibility this argument can also be provided as sig, although the long form is preferred. Note that this should not be confused with the generalized ufunc signature that is stored in the signature attribute of the of the ufunc object.
Attributes#
There are some informational attributes that universal functions possess. None of the attributes can be set.
__doc__ 
A docstring for each ufunc. The first part of the docstring is dynamically generated from the number of outputs, the name, and the number of inputs. The second part of the docstring is provided at creation time and stored with the ufunc. 
__name__ 
The name of the ufunc. 
The number of inputs. 

The number of outputs. 

The number of arguments. 

The number of types. 

Returns a list with types grouped input>output. 

The identity value. 

Definition of the core elements a generalized ufunc operates on. 
Methods#

Reduces 

Accumulate the result of applying the operator to all elements. 

Performs a (local) reduce with specified slices over a single axis. 

Apply the ufunc op to all pairs (a, b) with a in A and b in B. 

Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. 
Warning
A reducelike operation on an array with a datatype that has a
range “too small” to handle the result will silently wrap. One
should use dtype
to increase the size of the datatype over which
reduction takes place.
Available ufuncs#
There are currently more than 60 universal functions defined in
numpy
on one or more types, covering a wide variety of
operations. Some of these ufuncs are called automatically on arrays
when the relevant infix notation is used (e.g., add(a, b)
is called internally when a + b
is written and a or b is an
ndarray
). Nevertheless, you may still want to use the ufunc
call in order to use the optional output argument(s) to place the
output(s) in an object (or objects) of your choice.
Recall that each ufunc operates elementbyelement. Therefore, each scalar ufunc will be described as if acting on a set of scalar inputs to return a set of scalar outputs.
Note
The ufunc still returns its output(s) even if you use the optional output argument(s).
Math operations#

Add arguments elementwise. 

Subtract arguments, elementwise. 

Multiply arguments elementwise. 

Matrix product of two arrays. 

Divide arguments elementwise. 

Logarithm of the sum of exponentiations of the inputs. 

Logarithm of the sum of exponentiations of the inputs in base2. 

Divide arguments elementwise. 

Return the largest integer smaller or equal to the division of the inputs. 

Numerical negative, elementwise. 

Numerical positive, elementwise. 

First array elements raised to powers from second array, elementwise. 

First array elements raised to powers from second array, elementwise. 

Returns the elementwise remainder of division. 

Returns the elementwise remainder of division. 

Returns the elementwise remainder of division. 

Return elementwise quotient and remainder simultaneously. 

Calculate the absolute value elementwise. 

Compute the absolute values elementwise. 

Round elements of the array to the nearest integer. 

Returns an elementwise indication of the sign of a number. 

Compute the Heaviside step function. 

Return the complex conjugate, elementwise. 

Return the complex conjugate, elementwise. 

Calculate the exponential of all elements in the input array. 

Calculate 2**p for all p in the input array. 

Natural logarithm, elementwise. 

Base2 logarithm of x. 

Return the base 10 logarithm of the input array, elementwise. 

Calculate 

Return the natural logarithm of one plus the input array, elementwise. 

Return the nonnegative squareroot of an array, elementwise. 

Return the elementwise square of the input. 

Return the cuberoot of an array, elementwise. 

Return the reciprocal of the argument, elementwise. 

Returns the greatest common divisor of 

Returns the lowest common multiple of 
Tip
The optional output arguments can be used to help you save memory
for large calculations. If your arrays are large, complicated
expressions can take longer than absolutely necessary due to the
creation and (later) destruction of temporary calculation
spaces. For example, the expression G = A * B + C
is equivalent to
T1 = A * B; G = T1 + C; del T1
. It will be more quickly executed
as G = A * B; add(G, C, G)
which is the same as
G = A * B; G += C
.
Trigonometric functions#
All trigonometric functions use radians when an angle is called for. The ratio of degrees to radians is \(180^{\circ}/\pi.\)

Trigonometric sine, elementwise. 

Cosine elementwise. 

Compute tangent elementwise. 

Inverse sine, elementwise. 

Trigonometric inverse cosine, elementwise. 

Trigonometric inverse tangent, elementwise. 

Elementwise arc tangent of 

Given the "legs" of a right triangle, return its hypotenuse. 

Hyperbolic sine, elementwise. 

Hyperbolic cosine, elementwise. 

Compute hyperbolic tangent elementwise. 

Inverse hyperbolic sine elementwise. 

Inverse hyperbolic cosine, elementwise. 

Inverse hyperbolic tangent elementwise. 

Convert angles from radians to degrees. 

Convert angles from degrees to radians. 

Convert angles from degrees to radians. 

Convert angles from radians to degrees. 
Bittwiddling functions#
These function all require integer arguments and they manipulate the bitpattern of those arguments.

Compute the bitwise AND of two arrays elementwise. 

Compute the bitwise OR of two arrays elementwise. 

Compute the bitwise XOR of two arrays elementwise. 

Compute bitwise inversion, or bitwise NOT, elementwise. 

Shift the bits of an integer to the left. 

Shift the bits of an integer to the right. 
Comparison functions#

Return the truth value of (x1 > x2) elementwise. 

Return the truth value of (x1 >= x2) elementwise. 

Return the truth value of (x1 < x2) elementwise. 

Return the truth value of (x1 <= x2) elementwise. 

Return (x1 != x2) elementwise. 

Return (x1 == x2) elementwise. 
Warning
Do not use the Python keywords and
and or
to combine
logical array expressions. These keywords will test the truth
value of the entire array (not elementbyelement as you might
expect). Use the bitwise operators & and  instead.

Compute the truth value of x1 AND x2 elementwise. 

Compute the truth value of x1 OR x2 elementwise. 

Compute the truth value of x1 XOR x2, elementwise. 

Compute the truth value of NOT x elementwise. 
Warning
The bitwise operators & and  are the proper way to perform
elementbyelement array comparisons. Be sure you understand the
operator precedence: (a > 2) & (a < 5)
is the proper syntax because
a > 2 & a < 5
will result in an error due to the fact that 2 & a
is evaluated first.

Elementwise maximum of array elements. 
Tip
The Python function max()
will find the maximum over a onedimensional
array, but it will do so using a slower sequence interface. The reduce
method of the maximum ufunc is much faster. Also, the max()
method
will not give answers you might expect for arrays with greater than
one dimension. The reduce method of minimum also allows you to compute
a total minimum over an array.

Elementwise minimum of array elements. 
Warning
the behavior of maximum(a, b)
is different than that of max(a, b)
.
As a ufunc, maximum(a, b)
performs an elementbyelement comparison
of a and b and chooses each element of the result according to which
element in the two arrays is larger. In contrast, max(a, b)
treats
the objects a and b as a whole, looks at the (total) truth value of
a > b
and uses it to return either a or b (as a whole). A similar
difference exists between minimum(a, b)
and min(a, b)
.

Elementwise maximum of array elements. 

Elementwise minimum of array elements. 
Floating functions#
Recall that all of these functions work elementbyelement over an array, returning an array output. The description details only a single operation.

Test elementwise for finiteness (not infinity and not Not a Number). 

Test elementwise for positive or negative infinity. 

Test elementwise for NaN and return result as a boolean array. 

Test elementwise for NaT (not a time) and return result as a boolean array. 

Compute the absolute values elementwise. 

Returns elementwise True where signbit is set (less than zero). 

Change the sign of x1 to that of x2, elementwise. 

Return the next floatingpoint value after x1 towards x2, elementwise. 

Return the distance between x and the nearest adjacent number. 

Return the fractional and integral parts of an array, elementwise. 

Returns x1 * 2**x2, elementwise. 

Decompose the elements of x into mantissa and twos exponent. 

Returns the elementwise remainder of division. 

Return the floor of the input, elementwise. 

Return the ceiling of the input, elementwise. 

Return the truncated value of the input, elementwise. 