See also
Universal functions (ufunc) basics
A universal function (or ufunc for short) is a function thatoperates on ndarrays in an element-by-element fashion,supporting array broadcasting, typecasting, and several other standard features. Thatis, a ufunc is a “vectorized” wrapper for a functionthat takes a fixed number of specific inputs and produces a fixed number ofspecific outputs. For detailed information on universal functions, seeUniversal functions (ufunc) basics.
ufunc#
numpy.ufunc() | Functions that operate element by element on whole arrays. |
Optional keyword arguments#
All ufuncs take optional keyword arguments. Most of these representadvanced 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 keywordparameter. Keyword ‘out’ arguments are incompatible with positionalones.
New in version 1.10.
The ‘out’ keyword argument is expected to be a tuple with one entry peroutput (which can be None for arrays to be allocated by the ufunc).For ufuncs with a single output, passing a single array (instead of atuple holding a single array) is also valid.
Passing a single array in the ‘out’ keyword argument to a ufunc withmultiple 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 placesthat the broadcast ‘where’ is True. If ‘where’ is the scalar True (thedefault), then this corresponds to the entire output being filled.Note that outputs not explicitly filled are left with theiruninitialized values.
New in version 1.13.
Operations where ufunc input and output operands have memory overlap aredefined to be the same as for equivalent operations where thereis no memory overlap. Operations affected make temporary copiesas needed to eliminate data dependency. As detecting these casesis computationally expensive, a heuristic is used, which may in rarecases result in needless temporary copies. For operations where thedata dependency is simple enough for the heuristic to analyze,temporary copies will not be made even if the arrays overlap, if itcan 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, valuesof False indicate to leave the value in the output alone. This argumentcannot be used for generalized ufuncs as those take non-scalar input.
Note that if an uninitialized return array is created, values of Falsewill leave those values uninitialized.
axes
New in version 1.15.
A list of tuples with indices of axes a generalized ufunc should operateon. For instance, for a signature of (i,j),(j,k)->(i,k)
appropriatefor matrix multiplication, the base elements are two-dimensional matricesand 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 1-dimensional arrays(vectors), a single integer is accepted instead of a single-element tuple,and for generalized ufuncs for which all outputs are scalars, the outputtuples can be omitted.
axis
New in version 1.15.
A single axis over which a generalized ufunc should operate. This is ashort-cut for ufuncs that operate over a single, shared core dimension,equivalent to passing in axes
with entries of (axis,)
for eachsingle-core-dimension argument and ()
for all others. For instance,for a signature (i),(i)->()
, it is equivalent to passing inaxes=[(axis,), (axis,), ()]
.
keepdims
New in version 1.15.
If this is set to True, axes which are reduced over will be left in theresult as a dimension with size one, so that the result will broadcastcorrectly against the inputs. This option can only be used for generalizedufuncs that operate on inputs that all have the same number of coredimensions and with outputs that have no core dimensions, i.e., withsignatures like (i),(i)->()
or (m,m)->()
. If used, the location ofthe 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 compatibilitywith 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 aDeprecationWarning for calls which are allowed under the ‘unsafe’rules, but not under the ‘same_kind’ rules. From numpy 1.10 andonwards, 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 C-contiguous, ‘F’ meansF-contiguous, ‘A’ means F-contiguous if the inputs are F-contiguous andnot also not C-contiguous, C-contiguous otherwise, and ‘K’ means to matchthe 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 exactcalculation DTypes chosen may depend on the ufunc and the inputs may becast 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 strictarray, not a subtype.
signature
Either a Dtype, a tuple of DTypes, or a special signature stringindicating the input and output types of a ufunc.
This argument allows the user to specify exact DTypes to be used for thecalculation. Casting will be used as necessary. The actual DType of theinput arrays is not considered unless signature
is None
forthat array.
When all DTypes are fixed, a specific loop is chosen or an error raisedif no matching loop exists.If some DTypes are not specified and left None
, the behaviour maydepend on the ufunc.At this time, a list of available signatures is provided by the typesattribute of the ufunc. (This list may be missing DTypes not definedby NumPy.)
The signature
only specifies the DType class/type. For example, itcan specify that the operation should be datetime64
or float64
operation. It does not specify the datetime64
time-unit or thefloat64
byte-order.
For backwards compatibility this argument can also be provided as sig,although the long form is preferred. Note that this should not beconfused with the generalized ufunc signaturethat is stored in the signature attribute of the of the ufunc object.
Attributes#
There are some informational attributes that universal functionspossess. None of the attributes can be set.
__doc__ | A docstring for each ufunc. The first part of the docstring isdynamically generated from the number of outputs, the name, andthe number of inputs. The second part of the docstring isprovided at creation time and stored with the ufunc. |
__name__ | The name of the ufunc. |
ufunc.nin | The number of inputs. |
ufunc.nout | The number of outputs. |
ufunc.nargs | The number of arguments. |
ufunc.ntypes | The number of types. |
ufunc.types | Returns a list with types grouped input->output. |
ufunc.identity | The identity value. |
ufunc.signature | Definition of the core elements a generalized ufunc operates on. |
Methods#
ufunc.reduce(array[,axis,dtype,out,...]) | Reduces array's dimension by one, by applying ufunc along one axis. |
ufunc.accumulate(array[,axis,dtype,out]) | Accumulate the result of applying the operator to all elements. |
ufunc.reduceat(array,indices[,axis,...]) | Performs a (local) reduce with specified slices over a single axis. |
ufunc.outer(A,B,/,**kwargs) | Apply the ufunc op to all pairs (a, b) with a in A and b in B. |
ufunc.at(a,indices[,b]) | Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. |
Warning
A reduce-like operation on an array with a data-type that has arange “too small” to handle the result will silently wrap. Oneshould use dtype to increase the size of the data-type over whichreduction takes place.
Available ufuncs#
There are currently more than 60 universal functions defined innumpy on one or more types, covering a wide variety ofoperations. Some of these ufuncs are called automatically on arrayswhen the relevant infix notation is used (e.g., add(a, b)is called internally when a + b
is written and a or b is anndarray). Nevertheless, you may still want to use the ufunccall in order to use the optional output argument(s) to place theoutput(s) in an object (or objects) of your choice.
Recall that each ufunc operates element-by-element. Therefore, each scalarufunc will be described as if acting on a set of scalar inputs toreturn a set of scalar outputs.
Note
The ufunc still returns its output(s) even if you use the optionaloutput argument(s).
Math operations#
add(x1,x2,/[,out,where,casting,order,...]) | Add arguments element-wise. |
subtract(x1,x2,/[,out,where,casting,...]) | Subtract arguments, element-wise. |
multiply(x1,x2,/[,out,where,casting,...]) | Multiply arguments element-wise. |
matmul(x1,x2,/[,out,casting,order,...]) | Matrix product of two arrays. |
divide(x1,x2,/[,out,where,casting,...]) | Divide arguments element-wise. |
logaddexp(x1,x2,/[,out,where,casting,...]) | Logarithm of the sum of exponentiations of the inputs. |
logaddexp2(x1,x2,/[,out,where,casting,...]) | Logarithm of the sum of exponentiations of the inputs in base-2. |
true_divide(x1,x2,/[,out,where,...]) | Divide arguments element-wise. |
floor_divide(x1,x2,/[,out,where,...]) | Return the largest integer smaller or equal to the division of the inputs. |
negative(x,/[,out,where,casting,order,...]) | Numerical negative, element-wise. |
positive(x,/[,out,where,casting,order,...]) | Numerical positive, element-wise. |
power(x1,x2,/[,out,where,casting,...]) | First array elements raised to powers from second array, element-wise. |
float_power(x1,x2,/[,out,where,...]) | First array elements raised to powers from second array, element-wise. |
remainder(x1,x2,/[,out,where,casting,...]) | Returns the element-wise remainder of division. |
mod(x1,x2,/[,out,where,casting,order,...]) | Returns the element-wise remainder of division. |
fmod(x1,x2,/[,out,where,casting,...]) | Returns the element-wise remainder of division. |
divmod(x1,x2[,out1,out2],/[[,out,...]) | Return element-wise quotient and remainder simultaneously. |
absolute(x,/[,out,where,casting,order,...]) | Calculate the absolute value element-wise. |
fabs(x,/[,out,where,casting,order,...]) | Compute the absolute values element-wise. |
rint(x,/[,out,where,casting,order,...]) | Round elements of the array to the nearest integer. |
sign(x,/[,out,where,casting,order,...]) | Returns an element-wise indication of the sign of a number. |
heaviside(x1,x2,/[,out,where,casting,...]) | Compute the Heaviside step function. |
conj(x,/[,out,where,casting,order,...]) | Return the complex conjugate, element-wise. |
conjugate(x,/[,out,where,casting,...]) | Return the complex conjugate, element-wise. |
exp(x,/[,out,where,casting,order,...]) | Calculate the exponential of all elements in the input array. |
exp2(x,/[,out,where,casting,order,...]) | Calculate 2**p for all p in the input array. |
log(x,/[,out,where,casting,order,...]) | Natural logarithm, element-wise. |
log2(x,/[,out,where,casting,order,...]) | Base-2 logarithm of x. |
log10(x,/[,out,where,casting,order,...]) | Return the base 10 logarithm of the input array, element-wise. |
expm1(x,/[,out,where,casting,order,...]) | Calculate |
log1p(x,/[,out,where,casting,order,...]) | Return the natural logarithm of one plus the input array, element-wise. |
sqrt(x,/[,out,where,casting,order,...]) | Return the non-negative square-root of an array, element-wise. |
square(x,/[,out,where,casting,order,...]) | Return the element-wise square of the input. |
cbrt(x,/[,out,where,casting,order,...]) | Return the cube-root of an array, element-wise. |
reciprocal(x,/[,out,where,casting,...]) | Return the reciprocal of the argument, element-wise. |
gcd(x1,x2,/[,out,where,casting,order,...]) | Returns the greatest common divisor of |
lcm(x1,x2,/[,out,where,casting,order,...]) | Returns the lowest common multiple of |
Tip
The optional output arguments can be used to help you save memoryfor large calculations. If your arrays are large, complicatedexpressions can take longer than absolutely necessary due to thecreation and (later) destruction of temporary calculationspaces. For example, the expression G = A * B + C
is equivalent toT1 = A * B; G = T1 + C; del T1
. It will be more quickly executedas G = A * B; add(G, C, G)
which is the same asG = 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.\)
sin(x,/[,out,where,casting,order,...]) | Trigonometric sine, element-wise. |
cos(x,/[,out,where,casting,order,...]) | Cosine element-wise. |
tan(x,/[,out,where,casting,order,...]) | Compute tangent element-wise. |
arcsin(x,/[,out,where,casting,order,...]) | Inverse sine, element-wise. |
arccos(x,/[,out,where,casting,order,...]) | Trigonometric inverse cosine, element-wise. |
arctan(x,/[,out,where,casting,order,...]) | Trigonometric inverse tangent, element-wise. |
arctan2(x1,x2,/[,out,where,casting,...]) | Element-wise arc tangent of |
hypot(x1,x2,/[,out,where,casting,...]) | Given the "legs" of a right triangle, return its hypotenuse. |
sinh(x,/[,out,where,casting,order,...]) | Hyperbolic sine, element-wise. |
cosh(x,/[,out,where,casting,order,...]) | Hyperbolic cosine, element-wise. |
tanh(x,/[,out,where,casting,order,...]) | Compute hyperbolic tangent element-wise. |
arcsinh(x,/[,out,where,casting,order,...]) | Inverse hyperbolic sine element-wise. |
arccosh(x,/[,out,where,casting,order,...]) | Inverse hyperbolic cosine, element-wise. |
arctanh(x,/[,out,where,casting,order,...]) | Inverse hyperbolic tangent element-wise. |
degrees(x,/[,out,where,casting,order,...]) | Convert angles from radians to degrees. |
radians(x,/[,out,where,casting,order,...]) | Convert angles from degrees to radians. |
deg2rad(x,/[,out,where,casting,order,...]) | Convert angles from degrees to radians. |
rad2deg(x,/[,out,where,casting,order,...]) | Convert angles from radians to degrees. |
Bit-twiddling functions#
These function all require integer arguments and they manipulate thebit-pattern of those arguments.
bitwise_and(x1,x2,/[,out,where,...]) | Compute the bit-wise AND of two arrays element-wise. |
bitwise_or(x1,x2,/[,out,where,casting,...]) | Compute the bit-wise OR of two arrays element-wise. |
bitwise_xor(x1,x2,/[,out,where,...]) | Compute the bit-wise XOR of two arrays element-wise. |
invert(x,/[,out,where,casting,order,...]) | Compute bit-wise inversion, or bit-wise NOT, element-wise. |
left_shift(x1,x2,/[,out,where,casting,...]) | Shift the bits of an integer to the left. |
right_shift(x1,x2,/[,out,where,...]) | Shift the bits of an integer to the right. |
Comparison functions#
greater(x1,x2,/[,out,where,casting,...]) | Return the truth value of (x1 > x2) element-wise. |
greater_equal(x1,x2,/[,out,where,...]) | Return the truth value of (x1 >= x2) element-wise. |
less(x1,x2,/[,out,where,casting,...]) | Return the truth value of (x1 < x2) element-wise. |
less_equal(x1,x2,/[,out,where,casting,...]) | Return the truth value of (x1 <= x2) element-wise. |
not_equal(x1,x2,/[,out,where,casting,...]) | Return (x1 != x2) element-wise. |
equal(x1,x2,/[,out,where,casting,...]) | Return (x1 == x2) element-wise. |
Warning
Do not use the Python keywords and
and or
to combinelogical array expressions. These keywords will test the truthvalue of the entire array (not element-by-element as you mightexpect). Use the bitwise operators & and | instead.
logical_and(x1,x2,/[,out,where,...]) | Compute the truth value of x1 AND x2 element-wise. |
logical_or(x1,x2,/[,out,where,casting,...]) | Compute the truth value of x1 OR x2 element-wise. |
logical_xor(x1,x2,/[,out,where,...]) | Compute the truth value of x1 XOR x2, element-wise. |
logical_not(x,/[,out,where,casting,...]) | Compute the truth value of NOT x element-wise. |
Warning
The bit-wise operators & and | are the proper way to performelement-by-element array comparisons. Be sure you understand theoperator precedence: (a > 2) & (a < 5)
is the proper syntax becausea > 2 & a < 5
will result in an error due to the fact that 2 & a
is evaluated first.
maximum(x1,x2,/[,out,where,casting,...]) | Element-wise maximum of array elements. |
Tip
The Python function max()
will find the maximum over a one-dimensionalarray, but it will do so using a slower sequence interface. The reducemethod of the maximum ufunc is much faster. Also, the max()
methodwill not give answers you might expect for arrays with greater thanone dimension. The reduce method of minimum also allows you to computea total minimum over an array.
minimum(x1,x2,/[,out,where,casting,...]) | Element-wise 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 element-by-element comparisonof a and b and chooses each element of the result according to whichelement in the two arrays is larger. In contrast, max(a, b)
treatsthe objects a and b as a whole, looks at the (total) truth value ofa > b
and uses it to return either a or b (as a whole). A similardifference exists between minimum(a, b)
and min(a, b)
.
fmax(x1,x2,/[,out,where,casting,...]) | Element-wise maximum of array elements. |
fmin(x1,x2,/[,out,where,casting,...]) | Element-wise minimum of array elements. |
Floating functions#
Recall that all of these functions work element-by-element over anarray, returning an array output. The description details only asingle operation.
isfinite(x,/[,out,where,casting,order,...]) | Test element-wise for finiteness (not infinity and not Not a Number). |
isinf(x,/[,out,where,casting,order,...]) | Test element-wise for positive or negative infinity. |
isnan(x,/[,out,where,casting,order,...]) | Test element-wise for NaN and return result as a boolean array. |
isnat(x,/[,out,where,casting,order,...]) | Test element-wise for NaT (not a time) and return result as a boolean array. |
fabs(x,/[,out,where,casting,order,...]) | Compute the absolute values element-wise. |
signbit(x,/[,out,where,casting,order,...]) | Returns element-wise True where signbit is set (less than zero). |
copysign(x1,x2,/[,out,where,casting,...]) | Change the sign of x1 to that of x2, element-wise. |
nextafter(x1,x2,/[,out,where,casting,...]) | Return the next floating-point value after x1 towards x2, element-wise. |
spacing(x,/[,out,where,casting,order,...]) | Return the distance between x and the nearest adjacent number. |
modf(x[,out1,out2],/[[,out,where,...]) | Return the fractional and integral parts of an array, element-wise. |
ldexp(x1,x2,/[,out,where,casting,...]) | Returns x1 * 2**x2, element-wise. |
frexp(x[,out1,out2],/[[,out,where,...]) | Decompose the elements of x into mantissa and twos exponent. |
fmod(x1,x2,/[,out,where,casting,...]) | Returns the element-wise remainder of division. |
floor(x,/[,out,where,casting,order,...]) | Return the floor of the input, element-wise. |
ceil(x,/[,out,where,casting,order,...]) | Return the ceiling of the input, element-wise. |
trunc(x,/[,out,where,casting,order,...]) | Return the truncated value of the input, element-wise. |