Set printing options.
These options determine the way floating point numbers, arrays and other NumPy objects are displayed.
Number of digits of precision for floating point output (default 8). May be None if floatmode is not fixed, to print as many digits as necessary to uniquely specify the value.
Total number of array elements which trigger summarization rather than full repr (default 1000). To always use the full repr without summarization, pass sys.maxsize.
Number of array items in summary at beginning and end of each dimension (default 3).
The number of characters per line for the purpose of inserting line breaks (default 75).
If True, always print floating point numbers using fixed point notation, in which case numbers equal to zero in the current precision will print as zero. If False, then scientific notation is used when absolute value of the smallest number is < 1e-4 or the ratio of the maximum absolute value to the minimum is > 1e3. The default is False.
String representation of floating point not-a-number (default nan).
String representation of floating point infinity (default inf).
Controls printing of the sign of floating-point types. If ‘+’, always print the sign of positive values. If ‘ ‘, always prints a space (whitespace character) in the sign position of positive values. If ‘-’, omit the sign character of positive values. (default ‘-‘)
If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:
Other keys that can be used to set a group of types at once are:
Controls the interpretation of the precision option for floating-point types. Can take the following values (default maxprec_equal):
even if this would print more or fewer digits than necessary to specify the value uniquely.
to represent each value uniquely. Different elements may have a different number of digits. The value of the precision option is ignored.
an element can be uniquely represented with fewer digits only print it with that many.
but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements.
If set to the string ‘1.13’ enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. This also enables 1.21 legacy printing mode (described below).
If set to the string ‘1.21’ enables 1.21 legacy printing mode. This approximates numpy 1.21 print output of complex structured dtypes by not inserting spaces after commas that separate fields and after colons.
If set to False, disables legacy mode.
Unrecognized strings will be ignored with a warning for forward compatibility.
New in version 1.14.0.
Changed in version 1.22.0.
See also
formatter is always reset with a call to set_printoptions.
Use printoptions as a context manager to set the values temporarily.
Floating point precision can be set:
Long arrays can be summarised:
Small results can be suppressed:
A custom formatter can be used to display array elements as desired:
To put back the default options, you can use:
Also to temporarily override options, use printoptions as a context manager:


Set a Python function to be used when pretty printing arrays.
Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays.
If True (default), the function for pretty printing (__repr__) is set, if False the function that returns the default string representation (__str__) is set.
See also
We can reset the function to the default:
repr affects either pretty printing or normal string representation. Note that __repr__ is still affected by setting __str__ because the width of each array element in the returned string becomes equal to the length of the result of __str__().


Set the size of the buffer used in ufuncs.
Size of buffer.


Find the set difference of two arrays.
Return the unique values in ar1 that are not in ar2.
Input array.
Input comparison array.
If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
1D array of values in ar1 that are not in ar2. The result is sorted when assume_unique=False, but otherwise only sorted if the input is sorted.
See also
Module with a number of other functions for performing set operations on arrays.


Set how floating-point errors are handled.
Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by these settings.
Set treatment for all types of floating-point errors at once:
The default is not to change the current behavior.
Treatment for division by zero.
Treatment for floating-point overflow.
Treatment for floating-point underflow.
Treatment for invalid floating-point operation.
Dictionary containing the old settings.
See also
Set a callback function for the ‘call’ mode.
The floating-point exceptions are defined in the IEEE 754 standard [1]:
https://en.wikipedia.org/wiki/IEEE_754


Set the floating-point error callback function or log object.
There are two ways to capture floating-point error messages. The first is to set the error-handler to ‘call’, using seterr. Then, set the function to call using this function.
The second is to set the error-handler to ‘log’, using seterr. Floating-point errors then trigger a call to the ‘write’ method of the provided object.
Function to call upon floating-point errors (‘call’-mode) or object whose ‘write’ method is used to log such message (‘log’-mode).
The call function takes two arguments. The first is a string describing the type of error (such as “divide by zero”, “overflow”, “underflow”, or “invalid value”), and the second is the status flag. The flag is a byte, whose four least-significant bits indicate the type of error, one of “divide”, “over”, “under”, “invalid”:
In other words, flags = divide + 2*over + 4*under + 8*invalid.
If an object is provided, its write method should take one argument, a string.
The old error handler.
See also
Callback upon error:
Log error message:


Set the object that defines floating-point error handling.
The error object contains all information that defines the error handling behavior in NumPy. seterrobj is used internally by the other functions that set error handling behavior (seterr, seterrcall).
The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function].
The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for “invalid”, “under”, “over”, and “divide” (in that order). The printed string can be interpreted with
See also
For complete documentation of the types of floating-point exceptions and treatment options, see seterr.


Find the set exclusive-or of two arrays.
Return the sorted, unique values that are in only one (not both) of the input arrays.
Input arrays.
If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
Sorted 1D array of unique values that are in only one of the input arrays.


Return the shape of an array.
Input array.
The elements of the shape tuple give the lengths of the corresponding array dimensions.
See also
Equivalent array method.


Determine if two arrays share memory.
Warning
This function can be exponentially slow for some inputs, unless max_work is set to a finite number or MAY_SHARE_BOUNDS. If in doubt, use numpy.may_share_memory instead.
Input arrays
Effort to spend on solving the overlap problem (maximum number of candidate solutions to consider). The following special values are recognized:
The problem is solved exactly. In this case, the function returns True only if there is an element shared between the arrays. Finding the exact solution may take extremely long in some cases.
Only the memory bounds of a and b are checked.
Exceeded max_work.
See also
Checking whether two arrays share memory is NP-complete, and runtime may increase exponentially in the number of dimensions. Hence, max_work should generally be set to a finite number, as it is possible to construct examples that take extremely long to run:
Running np.shares_memory(x1, x2) without max_work set takes around 1 minute for this case. It is possible to find problems that take still significantly longer.


Signed integer type, compatible with C short.
'h'
numpy.int16: 16-bit signed integer (-32_768 to 32_767).


Show libraries in the system on which NumPy was built.
Print information about various resources (libraries, library directories, include directories, etc.) in the system on which NumPy was built.
See also
Returns the directory containing NumPy C header files.
Classes specifying the information to be printed are defined in the numpy.distutils.system_info module.
Information may include:
NumPy BLAS/LAPACK Installation Notes
Installing a numpy wheel (pip install numpy or force it via pip install numpy --only-binary :numpy: numpy) includes an OpenBLAS implementation of the BLAS and LAPACK linear algebra APIs. In this case, library_dirs reports the original build time configuration as compiled with gcc/gfortran; at run time the OpenBLAS library is in site-packages/numpy.libs/ (linux), or site-packages/numpy/.dylibs/ (macOS), or site-packages/numpy/.libs/ (windows).
Installing numpy from source (pip install numpy --no-binary numpy) searches for BLAS and LAPACK dynamic link libraries at build time as influenced by environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER; or the optional file ~/.numpy-site.cfg. NumPy remembers those locations and expects to load the same libraries at run-time. In NumPy 1.21+ on macOS, ‘accelerate’ (Apple’s Accelerate BLAS library) is in the default build-time search order after ‘openblas’.


Returns an element-wise indication of the sign of a number.
The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0. nan is returned for nan inputs.
For complex inputs, the sign function returns sign(x.real) + 0j if x.real != 0 else sign(x.imag) + 0j.
complex(nan, 0) is returned for complex nan inputs.
Input values.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The sign of x. This is a scalar if x is a scalar.
There is more than one definition of sign in common use for complex numbers. The definition used here is equivalent to \(x/\sqrt{x*x}\) which is different from a common alternative, \(x/|x|\).


Returns element-wise True where signbit is set (less than zero).
The input value(s).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Output array, or reference to out if that was supplied. This is a scalar if x is a scalar.


Trigonometric sine, element-wise.
Angle, in radians (\(2 \pi\) rad equals 360 degrees).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The sine of each element of x. This is a scalar if x is a scalar.
See also
The sine is one of the fundamental functions of trigonometry (the mathematical study of triangles). Consider a circle of radius 1 centered on the origin. A ray comes in from the \(+x\) axis, makes an angle at the origin (measured counter-clockwise from that axis), and departs from the origin. The \(y\) coordinate of the outgoing ray’s intersection with the unit circle is the sine of that angle. It ranges from -1 for \(x=3\pi / 2\) to +1 for \(\pi / 2.\) The function has zeroes where the angle is a multiple of \(\pi\). Sines of angles between \(\pi\) and \(2\pi\) are negative. The numerous properties of the sine and related functions are included in any standard trigonometry text.
Print sine of one angle:
Print sines of an array of angles given in degrees:
Plot the sine function:


Return the normalized sinc function.
The sinc function is \(\sin(\pi x)/(\pi x)\).
Note
Note the normalization factor of pi used in the definition. This is the most commonly used definition in signal processing. Use sinc(x / np.pi) to obtain the unnormalized sinc function \(\sin(x)/(x)\) that is more common in mathematics.
Array (possibly multi-dimensional) of values for which to to calculate sinc(x).
sinc(x), which has the same shape as the input.
sinc(0) is the limit value 1.
The name sinc is short for “sine cardinal” or “sinus cardinalis”.
The sinc function is used in various signal processing applications, including in anti-aliasing, in the construction of a Lanczos resampling filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function.
Weisstein, Eric W. “Sinc Function.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/SincFunction.html
Wikipedia, “Sinc function”, https://en.wikipedia.org/wiki/Sinc_function


Single-precision floating-point number type, compatible with C float.
'f'
numpy.float32: 32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa.


Hyperbolic sine, element-wise.
Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The corresponding hyperbolic sine values. This is a scalar if x is a scalar.
If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83.


Return a sorted copy of an array.
Array to be sorted.
Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort or radix sort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.
Changed in version 1.15.0.: The ‘stable’ option was added.
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
Array of the same type and shape as a.
See also
Method to sort an array in-place.
Indirect sort.
Indirect stable sort on multiple keys.
Find elements in a sorted array.
Partial sort.
The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The four algorithms implemented in NumPy have the following properties:
kind
speed
worst case
work space
stable
‘quicksort’
1
O(n^2)
0
no
‘heapsort’
3
O(n*log(n))
0
no
‘mergesort’
2
O(n*log(n))
~n/2
yes
‘timsort’
2
O(n*log(n))
~n/2
yes
Note
The datatype determines which of ‘mergesort’ or ‘timsort’ is actually used, even if ‘mergesort’ is specified. User selection at a finer scale is not currently available.
All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting along any other axis.
The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts.
Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is:
where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before.
New in version 1.12.0.
quicksort has been changed to introsort. When sorting does not make enough progress it switches to heapsort. This implementation makes quicksort O(n*log(n)) in the worst case.
‘stable’ automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with ‘mergesort’ is currently mapped to timsort or radix sort depending on the data type. API forward compatibility currently limits the ability to select the implementation and it is hardwired for the different data types.
New in version 1.17.0.
Timsort is added for better performance on already or nearly sorted data. On random data timsort is almost identical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen. For timsort details, refer to CPython listsort.txt. ‘mergesort’ and ‘stable’ are mapped to radix sort for integer data types. Radix sort is an O(n) sort instead of O(n log n).
Changed in version 1.18.0.
NaT now sorts to the end of arrays for consistency with NaN.
Use the order keyword to specify a field to use when sorting a structured array:
Sort by age, then height if ages are equal:


Sort a complex array using the real part first, then the imaginary part.
Input array
Always returns a sorted complex array.


Print or write to a file the source code for a NumPy object.
The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information.
Input object. This can be any object (function, class, module, …).
If output not supplied then source code is printed to screen (sys.stdout). File object must be created with either write ‘w’ or append ‘a’ modes.
See also
The source code is only returned for objects written in Python.


Return the distance between x and the nearest adjacent number.
Values to find the spacing of.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The spacing of values of x. This is a scalar if x is a scalar.
It can be considered as a generalization of EPS: spacing(np.float64(1)) == np.finfo(np.float64).eps, and there should not be any representable number between x + spacing(x) and x for any finite x.
Spacing of +- inf and NaN is NaN.


Split an array into multiple sub-arrays as views into ary.
Array to be divided into sub-arrays.
If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.
If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in
If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.
The axis along which to split, default is 0.
A list of sub-arrays as views into ary.
If indices_or_sections is given as an integer, but a split does not result in equal division.
See also
Split an array into multiple sub-arrays of equal or near-equal size. Does not raise an exception if an equal division cannot be made.
Split array into multiple sub-arrays horizontally (column-wise).
Split array into multiple sub-arrays vertically (row wise).
Split array into multiple sub-arrays along the 3rd axis (depth).
Join a sequence of arrays along an existing axis.
Join a sequence of arrays along a new axis.
Stack arrays in sequence horizontally (column wise).
Stack arrays in sequence vertically (row wise).
Stack arrays in sequence depth wise (along third dimension).


Return the non-negative square-root of an array, element-wise.
The values whose square-roots are required.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar.
See also
A version which returns complex numbers when given negative reals.
sqrt has–consistent with common convention–as its branch cut the real “interval” [-inf, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous.


Return the element-wise square of the input.
Input data.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar.
See also


Remove axes of length one from a.
Input data.
New in version 1.7.0.
Selects a subset of the entries of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised.
The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a. Note that if all axes are squeezed, the result is a 0d array and not a scalar.
If axis is not None, and an axis being squeezed is not of length 1
See also
The inverse operation, adding entries of length one
Insert, remove, and combine dimensions, and resize existing ones


Join a sequence of arrays along a new axis.
The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.
New in version 1.10.0.
Each array must have the same shape.
The axis in the result array along which the input arrays are stacked.
If provided, the destination to place the result. The shape must be correct, matching that of what stack would have returned if no out argument were specified.
The stacked array has one more dimension than the input arrays.
See also
Join a sequence of arrays along an existing axis.
Assemble an nd-array from nested lists of blocks.
Split array into a list of multiple sub-arrays of equal size.


Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.
Calculate the standard deviation of these values.
Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.
New in version 1.7.0.
If this is a tuple of ints, a standard deviation is performed over multiple axes, instead of a single axis or all the axes as before.
Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.
Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary.
Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
Elements to include in the standard deviation. See reduce for details.
New in version 1.20.0.
If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array.
See also
The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std = sqrt(mean(x)), where x = abs(a - a.mean())**2.
The average squared deviation is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard deviation per se.
Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real and nonnegative.
For floating-point input, the std is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue.
In single precision, std() can be inaccurate:
Computing the standard deviation in float64 is more accurate:
Specifying a where argument:


A unicode string.
When used in arrays, this type strips trailing null codepoints.
Unlike the builtin str, this supports the Buffer Protocol, exposing its contents as UCS4:
'U'
numpy.unicode_


Subtract arguments, element-wise.
The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.
Equivalent to x1 - x2 in terms of array broadcasting.
The - operator can be used as a shorthand for np.subtract on ndarrays.


Sum of array elements over a given axis.
Elements to sum.
Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.
New in version 1.7.0.
If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
Starting value for the sum. See reduce for details.
New in version 1.15.0.
Elements to include in the sum. See reduce for details.
New in version 1.17.0.
An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.
See also
Equivalent method.
Equivalent functionality of add.
Cumulative sum of array elements.
Integration of array values using the composite trapezoidal rule.
Arithmetic is modular when using integer types, and no error is raised on overflow.
The sum of an empty array is the neutral element 0:
For floating point numbers the numerical precision of sum (and np.add.reduce) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no axis is given. When axis is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python’s math.fsum function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as float32, numerical errors can become significant. In such cases it can be advisable to use dtype=”float64” to use a higher precision for the output.
If the accumulator is too small, overflow occurs:
You can also start the sum with a value other than zero:


Interchange two axes of an array.
Input array.
First axis.
Second axis.
For NumPy >= 1.10.0, if a is an ndarray, then a view of a is returned; otherwise a new array is created. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned.


Take elements from an array along an axis.
When axis is not None, this function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...].
Explained without fancy indexing, this is equivalent to the following use of ndindex, which sets each of ii, jj, and kk to a tuple of indices:
The source array.
The indices of the values to extract.
New in version 1.8.0.
Also allow scalars for indices.
The axis over which to select values. By default, the flattened input array is used.
If provided, the result will be placed in this array. It should be of the appropriate shape and dtype. Note that out is always buffered if mode=’raise’; use other modes for better performance.
Specifies how out-of-bounds indices will behave.
‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.
The returned array has the same type as a.
See also
Take elements using a boolean mask
equivalent method
Take elements by matching the array and the index arrays
By eliminating the inner loop in the description above, and using s_ to build simple slice objects, take can be expressed in terms of applying fancy indexing to each 1-d slice:
For this reason, it is equivalent to (but faster than) the following use of apply_along_axis:
In this example if a is an ndarray, “fancy” indexing can be used.
If indices is not one dimensional, the output also has these dimensions.


Take values from the input array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to look up values in the latter. These slices can be different lengths.
Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function.
New in version 1.15.0.
Source array
Indices to take along each 1d slice of arr. This must match the dimension of arr, but dimensions Ni and Nj only need to broadcast against arr.
The axis to take 1d slices along. If axis is None, the input array is treated as if it had first been flattened to 1d, for consistency with sort and argsort.
The indexed result.
See also
Take along an axis, using the same indices for every 1d slice
Put values into the destination array by matching 1d index and data slices
This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii and kk to a tuple of indices:
Equivalently, eliminating the inner loop, the last two lines would be:
For this sample array
We can sort either by using sort directly, or argsort and this function
The same works for max and min, if you expand the dimensions:
If we want to get the max and min at the same time, we can stack the indices first


Compute tangent element-wise.
Equivalent to np.sin(x)/np.cos(x) element-wise.
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The corresponding tangent values. This is a scalar if x is a scalar.
If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972.


Compute hyperbolic tangent element-wise.
Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The corresponding hyperbolic tangent values. This is a scalar if x is a scalar.
If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83. https://personal.math.ubc.ca/~cbm/aands/page_83.htm
Wikipedia, “Hyperbolic function”, https://en.wikipedia.org/wiki/Hyperbolic_function


Compute tensor dot product along specified axes.
Given two tensors, a and b, and an array_like object containing two array_like objects, (a_axes, b_axes), sum the products of a’s and b’s elements (components) over the axes specified by a_axes and b_axes. The third argument can be a single non-negative integer_like scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over.
Tensors to “dot”.
The tensor dot product of the input.
See also
When axes is integer_like, the sequence for evaluation will be: first the -Nth axis in a and 0th axis in b, and the -1th axis in a and Nth axis in b last.
When there is more than one axis to sum over - and they are not the last (first) axes of a (b) - the argument axes should consist of two sequences of the same length, with the first axis to sum over given first in both sequences, the second axis second, and so forth.
The shape of the result consists of the non-contracted axes of the first tensor, followed by the non-contracted axes of the second.
A “traditional” example:
An extended example taking advantage of the overloading of + and *:


Until the 1.15 release, NumPy used the nose testing framework, it now uses the pytest framework. The older framework is still maintained in order to support downstream projects that use the old numpy framework, but all tests for NumPy should use pytest.
Our goal is that every module and package in NumPy should have a thorough set of unit tests. These tests should exercise the full functionality of a given routine as well as its robustness to erroneous or unexpected input arguments. Well-designed tests with good coverage make an enormous difference to the ease of refactoring. Whenever a new bug is found in a routine, you should write a new test for that specific case and add it to the test suite to prevent that bug from creeping back in unnoticed.
Note
SciPy uses the testing framework from numpy.testing, so all of the NumPy examples shown below are also applicable to SciPy
NumPy can be tested in a number of ways, choose any way you feel comfortable.
You can test an installed NumPy by numpy.test, for example, To run NumPy’s full test suite, use the following:
The test method may take two or more arguments; the first label is a string specifying what should be tested and the second verbose is an integer giving the level of output verbosity. See the docstring numpy.test for details. The default value for label is ‘fast’ - which will run the standard tests. The string ‘full’ will run the full battery of tests, including those identified as being slow to run. If verbose is 1 or less, the tests will just show information messages about the tests that are run; but if it is greater than 1, then the tests will also provide warnings on missing tests. So if you want to run every test and get messages about which modules don’t have tests:
Finally, if you are only interested in testing a subset of NumPy, for example, the core module, use the following:
If you want to build NumPy in order to work on NumPy itself, use runtests.py.To run NumPy’s full test suite:
Testing a subset of NumPy:
For detailed info on testing, see Testing builds
Run tests using your favourite IDE such as vscode or pycharm
If you are writing a package that you’d like to become part of NumPy, please write the tests as you develop the package. Every Python module, extension module, or subpackage in the NumPy package directory should have a corresponding test_<name>.py file. Pytest examines these files for test methods (named test*) and test classes (named Test*).
Suppose you have a NumPy module numpy/xxx/yyy.py containing a function zzz(). To test this function you would create a test module called test_yyy.py. If you only need to test one aspect of zzz, you can simply add a test function:
More often, we need to group a number of tests together, so we create a test class:
Within these test methods, assert and related functions are used to test whether a certain assumption is valid. If the assertion fails, the test fails. pytest internally rewrites the assert statement to give informative output when it fails, so should be preferred over the legacy variant numpy.testing.assert_. Whereas plain assert statements are ignored when running Python in optimized mode with -O, this is not an issue when running tests with pytest.
Similarly, the pytest functions pytest.raises and pytest.warns should be preferred over their legacy counterparts numpy.testing.assert_raises and numpy.testing.assert_warns, since the pytest variants are more broadly used and allow more explicit targeting of warnings and errors when used with the match regex.
Note that test_ functions or methods should not have a docstring, because that makes it hard to identify the test from the output of running the test suite with verbose=2 (or similar verbosity setting). Use plain comments (#) if necessary.
Also since much of NumPy is legacy code that was originally written without unit tests, there are still several modules that don’t have tests yet. Please feel free to choose one of these modules and develop tests for it.
NumPy exposes a rich C-API . These are tested using c-extension modules written “as-if” they know nothing about the internals of NumPy, rather using the official C-API interfaces only. Examples of such modules are tests for a user-defined rational dtype in _rational_tests or the ufunc machinery tests in _umath_tests which are part of the binary distribution. Starting from version 1.21, you can also write snippets of C code in tests that will be compiled locally into c-extension modules and loaded into python.
Build and imports a c-extension module modname from a list of function fragments functions.
Each fragment is a sequence of func_name, calling convention, snippet.
Code to preceed the rest, usually extra #include or #define macros.
Where to build the module, usually a temporary directory
Extra directories to find include files when compiling
Code to appear in the module PyMODINIT_FUNC
The module will have been loaded and is ready for use
Unlabeled tests like the ones above are run in the default numpy.test() run. If you want to label your test as slow - and therefore reserved for a full numpy.test(label='full') run, you can label it with pytest.mark.slow:
Similarly for methods:
Testing looks for module-level or class-level setup and teardown functions by name; thus:
Setup and teardown functions to functions and methods are known as “fixtures”, and their use is not encouraged.
One very nice feature of testing is allowing easy testing across a range of parameters - a nasty problem for standard unit tests. Use the pytest.mark.parametrize decorator.
Doctests are a convenient way of documenting the behavior of a function and allowing that behavior to be tested at the same time. The output of an interactive Python session can be included in the docstring of a function, and the test framework can run the example and compare the actual output to the expected output.
The doctests can be run by adding the doctests argument to the test() call; for example, to run all tests (including doctests) for numpy.lib:
The doctests are run as if they are in a fresh Python instance which has executed import numpy as np. Tests that are part of a NumPy subpackage will have that subpackage already imported. E.g. for a test in numpy/linalg/tests/, the namespace will be created such that from numpy import linalg has already executed.
Rather than keeping the code and the tests in the same directory, we put all the tests for a given subpackage in a tests/ subdirectory. For our example, if it doesn’t already exist you will need to create a tests/ directory in numpy/xxx/. So the path for test_yyy.py is numpy/xxx/tests/test_yyy.py.
Once the numpy/xxx/tests/test_yyy.py is written, its possible to run the tests by going to the tests/ directory and typing:
Or if you add numpy/xxx/tests/ to the Python path, you could run the tests interactively in the interpreter like this:
Usually, however, adding the tests/ directory to the python path isn’t desirable. Instead it would better to invoke the test straight from the module xxx. To this end, simply place the following lines at the end of your package’s __init__.py file:
You will also need to add the tests directory in the configuration section of your setup.py:
Now you can do the following to test your module:
Also, when invoking the entire NumPy test suite, your tests will be found and run:
If you have a collection of tests that must be run multiple times with minor variations, it can be helpful to create a base class containing all the common tests, and then create a subclass for each variation. Several examples of this technique exist in NumPy; below are excerpts from one in numpy/linalg/tests/test_linalg.py:
In this case, we wanted to test solving a linear algebra problem using matrices of several data types, using linalg.solve and linalg.inv. The common test cases (for single-precision, double-precision, etc. matrices) are collected in LinalgTestCase.
Sometimes you might want to skip a test or mark it as a known failure, such as when the test suite is being written before the code it’s meant to test, or if a test only fails on a particular architecture.
To skip a test, simply use skipif:
The test is marked as skipped if SkipMyTest evaluates to nonzero, and the message in verbose test output is the second argument given to skipif. Similarly, a test can be marked as a known failure by using xfail:
Of course, a test can be unconditionally skipped or marked as a known failure by using skip or xfail without argument, respectively.
A total of the number of skipped and known failing tests is displayed at the end of the test run. Skipped tests are marked as 'S' in the test results (or 'SKIPPED' for verbose > 1), and known failing tests are marked as 'x' (or 'XFAIL' if verbose >
1).
Tests on random data are good, but since test failures are meant to expose new bugs or regressions, a test that passes most of the time but fails occasionally with no code changes is not helpful. Make the random data deterministic by setting the random number seed before generating it. Use either Python’s random.seed(some_number) or NumPy’s numpy.random.seed(some_number), depending on the source of random numbers.
Alternatively, you can use Hypothesis to generate arbitrary data. Hypothesis manages both Python’s and Numpy’s random seeds for you, and provides a very concise and powerful way to describe data (including hypothesis.extra.numpy, e.g. for a set of mutually-broadcastable shapes).
The advantages over random generation include tools to replay and share failures without requiring a fixed seed, reporting minimal examples for each failure, and better-than-naive-random techniques for triggering bugs.
Pytest test runner.
A test function is typically added to a package’s __init__.py like so:
Calling this test function finds and runs all tests associated with the module and all its sub-modules.
The name of the module to test.
Unlike the previous nose-based implementation, this class is not publicly exposed as it performs some numpy-specific warning suppression.
Full path to the package to test.


Context manager and decorator doing much the same as warnings.catch_warnings.
However, it also provides a filter mechanism to work around https://bugs.python.org/issue4180.
This bug causes Python before 3.4 to not reliably show warnings again after they have been ignored once (even within catch_warnings). It means that no “ignore” filter can be used easily, since following tests might need to see the warning. Additionally it allows easier specificity for testing warnings and can be nested.
One of “always”, “once”, “module”, or “location”. Analogous to the usual warnings module filter mode, it is useful to reduce noise mostly on the outmost level. Unsuppressed and unrecorded warnings will be forwarded based on this rule. Defaults to “always”. “location” is equivalent to the warnings “default”, match by exact location the warning warning originated from.
Filters added inside the context manager will be discarded again when leaving it. Upon entering all filters defined outside a context will be applied automatically.
When a recording filter is added, matching warnings are stored in the log attribute as well as in the list returned by record.
If filters are added and the module keyword is given, the warning registry of this module will additionally be cleared when applying it, entering the context, or exiting it. This could cause warnings to appear a second time after leaving the context if they were configured to be printed once (default) and were already printed before the context was entered.
Nesting this context manager will work as expected when the forwarding rule is “always” (default). Unfiltered and unrecorded warnings will be passed out and be matched by the outer level. On the outmost level they will be printed (or caught by another warnings context). The forwarding rule argument can modify this behaviour.
Like catch_warnings this context manager is not threadsafe.
With a context manager:
Or as a decorator:
__call__(func)
Function decorator to apply certain suppressions to a whole function.
filter([category, message, module])
Add a new suppressing filter or apply it if the state is entered.
record([category, message, module])
Append a new recording filter or apply it if the state is entered.


Construct an array by repeating A the number of times given by reps.
If reps has length d, the result will have dimension of max(d, A.ndim).
If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.
If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).
Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions.
The input array.
The number of repetitions of A along each axis.
The tiled output array.
See also
Repeat elements of an array.
Broadcast an array to a new shape


A timedelta stored as a 64-bit integer.
See Datetimes and Timedeltas for more information.
'm'


Return the sum along diagonals of the array.
If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i.
If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.
Input array, from which the diagonals are taken.
Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0.
Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a.
Determines the data-type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and a is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of a.
Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output.
If a is 2-D, the sum along the diagonal is returned. If a has larger dimensions, then an array of sums along diagonals is returned.
See also


Reverse or permute the axes of an array; returns the modified array.
For an array a with two axes, transpose(a) gives the matrix transpose.
Refer to numpy.ndarray.transpose for full documentation.
Input array.
If specified, it must be a tuple or list which contains a permutation of [0,1,..,N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to range(a.ndim)[::-1], which reverses the order of the axes.
a with its axes permuted. A view is returned whenever possible.
See also
Equivalent method
Use transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument.
Transposing a 1-D array returns an unchanged view of the original array.


Integrate along the given axis using the composite trapezoidal rule.
If x is provided, the integration happens in sequence along its elements - they are not sorted.
Integrate y (x) along each 1d slice on the given axis, compute \(\int y(x) dx\). When x is specified, this integrates along the parametric curve, computing \(\int_t y(t) dt = \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt\).
Input array to integrate.
The sample points corresponding to the y values. If x is None, the sample points are assumed to be evenly spaced dx apart. The default is None.
The spacing between sample points when x is None. The default is 1.
The axis along which to integrate.
Definite integral of ‘y’ = n-dimensional array as approximated along a single axis by the trapezoidal rule. If ‘y’ is a 1-dimensional array, then the result is a float. If ‘n’ is greater than 1, then the result is an ‘n-1’ dimensional array.
See also
Image [2] illustrates trapezoidal rule – y-axis locations of points will be taken from y array, by default x-axis distances between points will be 1.0, alternatively they can be provided with x array or with dx scalar. Return value will be equal to combined area under the red lines.
Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
Illustration image: https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
Using a decreasing x corresponds to integrating in reverse:
More generally x is used to integrate along a parametric curve. This finds the area of a circle, noting we repeat the sample which closes the curve:


An array with ones at and below the given diagonal and zeros elsewhere.
Number of rows in the array.
Number of columns in the array. By default, M is taken equal to N.
The sub-diagonal at and below which the array is filled. k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0.
Data type of the returned array. The default is float.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Array with its lower triangle filled with ones and zero elsewhere; in other words T[i,j] == 1 for j <= i + k, 0 otherwise.


Lower triangle of an array.
Return a copy of an array with elements above the k-th diagonal zeroed. For arrays with ndim exceeding 2, tril will apply to the final two axes.
Input array.
Diagonal above which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.
Lower triangle of m, of same shape and data-type as m.
See also
same thing, only for the upper triangle


Return the indices for the lower-triangle of an (n, m) array.
The row dimension of the arrays for which the returned indices will be valid.
Diagonal offset (see tril for details).
New in version 1.9.0.
The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.
The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array.
See also
similar function, for upper-triangular.
generic function accepting an arbitrary mask function.
New in version 1.4.0.
Compute two different sets of indices to access 4x4 arrays, one for the lower triangular part starting at the main diagonal, and one starting two diagonals further right:
Here is how they can be used with a sample array:
Both for indexing:
And for assigning values:
These cover almost the whole array (two diagonals right of the main one):


Return the indices for the lower-triangle of arr.
See tril_indices for full details.
The indices will be valid for square arrays whose dimensions are the same as arr.
Diagonal offset (see tril for details).
See also
New in version 1.4.0.


Trim the leading and/or trailing zeros from a 1-D array or sequence.
Input array.
A string with ‘f’ representing trim from front and ‘b’ to trim from back. Default is ‘fb’, trim zeros from both front and back of the array.
The result of trimming the input. The input data type is preserved.
The input data type is preserved, list/tuple in means list/tuple out.


Upper triangle of an array.
Return a copy of an array with the elements below the k-th diagonal zeroed. For arrays with ndim exceeding 2, triu will apply to the final two axes.
Please refer to the documentation for tril for further details.
See also
lower triangle of an array


Return the indices for the upper-triangle of an (n, m) array.
The size of the arrays for which the returned indices will be valid.
Diagonal offset (see triu for details).
New in version 1.9.0.
The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.
The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array. Can be used to slice a ndarray of shape(n, n).
See also
similar function, for lower-triangular.
generic function accepting an arbitrary mask function.
New in version 1.4.0.
Compute two different sets of indices to access 4x4 arrays, one for the upper triangular part starting at the main diagonal, and one starting two diagonals further right:
Here is how they can be used with a sample array:
Both for indexing:
And for assigning values:
These cover only a small part of the whole array (two diagonals right of the main one):


Return the indices for the upper-triangle of arr.
See triu_indices for full details.
The indices will be valid for square arrays.
Diagonal offset (see triu for details).
Indices for the upper-triangle of arr.
See also
New in version 1.4.0.


Returns a true division of the inputs, element-wise.
Unlike ‘floor division’, true division adjusts the output type to present the best answer, regardless of input types.
Dividend array.
Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
This is a scalar if both x1 and x2 are scalars.
In Python, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python.
The / operator can be used as a shorthand for np.true_divide on ndarrays.


Return the truncated value of the input, element-wise.
The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. In short, the fractional part of the signed number x is discarded.
Input data.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The truncated value of each element in x. This is a scalar if x is a scalar.
See also
New in version 1.3.0.


Return a description for the given data type code.
Data type code.
Description of the input data type code.
See also


New in version 1.20.
Large parts of the NumPy API have PEP-484-style type annotations. In addition a number of type aliases are available to users, most prominently the two below:
New in version 1.21.
A mypy plugin for managing a number of platform-specific annotations. Its functionality can be split into three distinct parts:
Assigning the (platform-dependent) precision of c_intp. Without the plugin the type will default to ctypes.c_int64.
New in version 1.22.
To enable the plugin, one must add it to their mypy configuration file:
NumPy is very flexible. Trying to describe the full range of possibilities statically would result in types that are not very helpful. For that reason, the typed NumPy API is often stricter than the runtime NumPy API. This section describes some notable differences.
The ArrayLike type tries to avoid creating object arrays. For example,
is valid NumPy code which will create a 0-dimensional object array. Type checkers will complain about the above example when using the NumPy types however. If you really intended to do the above, then you can either use a # type: ignore comment:
or explicitly type the array like object as Any:
It’s possible to mutate the dtype of an array at runtime. For example, the following code is valid:
This sort of mutation is not allowed by the types. Users who want to write statically typed code should instead use the numpy.ndarray.view method to create a view of the array with a different dtype.
The DTypeLike type tries to avoid creation of dtype objects using dictionary of fields like below:
Although this is valid NumPy code, the type checker will complain about it, since its usage is discouraged. Please see : Data type objects
The precision of numpy.number subclasses is treated as a covariant generic parameter (see NBitBase), simplifying the annotating of processes involving precision-based casting.
Consequently, the likes of float16, float32 and float64 are still sub-types of floating, but, contrary to runtime, they’re not necessarily considered as sub-classes.
The timedelta64 class is not considered a subclass of signedinteger, the former only inheriting from generic while static type checking.
During runtime numpy aggressively casts any passed 0D arrays into their corresponding generic instance. Until the introduction of shape typing (see PEP 646) it is unfortunately not possible to make the necessary distinction between 0D and >0D arrays. While thus not strictly correct, all operations are that can potentially perform a 0D-array -> scalar cast are currently annotated as exclusively returning an ndarray.
If it is known in advance that an operation _will_ perform a 0D-array -> scalar cast, then one can consider manually remedying the situation with either typing.cast or a # type: ignore comment.
The dtype of numpy.recarray, and the numpy.rec functions in general, can be specified in one of two ways:
These two approaches are currently typed as being mutually exclusive, i.e. if dtype is specified than one may not specify formats. While this mutual exclusivity is not (strictly) enforced during runtime, combining both dtype specifiers can lead to unexpected or even downright buggy behavior.
A Union representing objects that can be coerced into an ndarray.
Among others this includes the likes of:
New in version 1.20.
See Also
Any scalar or sequence that can be interpreted as an ndarray.
A Union representing objects that can be coerced into a dtype.
Among others this includes the likes of:
New in version 1.20.
See Also
A comprehensive overview of all objects that can be coerced into data types.
A generic version of np.ndarray[Any, np.dtype[+ScalarType]].
Can be used during runtime for typing arrays with a given dtype and unspecified shape.
New in version 1.21.
A type representing numpy.number precision during static type checking.
Used exclusively for the purpose static type checking, NBitBase represents the base of a hierarchical set of subclasses. Each subsequent subclass is herein used for representing a lower level of precision, e.g. 64Bit > 32Bit > 16Bit.
New in version 1.20.
Below is a typical usage example: NBitBase is herein used for annotating a function that takes a float and integer of arbitrary precision as arguments and returns a new float of whichever precision is largest (e.g. np.float16 + np.int64 -> np.float64).


A Union representing objects that can be coerced into a dtype.
Among others this includes the likes of:
New in version 1.20.
See Also
A comprehensive overview of all objects that can be coerced into data types.


A generic version of np.ndarray[Any, np.dtype[+ScalarType]].
Can be used during runtime for typing arrays with a given dtype and unspecified shape.
New in version 1.21.


Unsigned integer type, compatible with C unsigned char.
'B'
numpy.uint8: 8-bit unsigned integer (0 to 255).


Functions that operate element by element on whole arrays.
To see the documentation for a specific ufunc, use info. For example, np.info(np.sin). Because ufuncs are written in C (for speed) and linked into Python with NumPy’s ufunc facility, Python’s help() function finds this page whenever help() is called on a ufunc.
A detailed explanation of ufuncs can be found in the docs for Universal functions (ufunc).
Calling ufuncs: op(*x[, out], where=True, **kwargs)
Apply op to the arguments *x elementwise, broadcasting the arguments.
The broadcasting rules are:
Input arrays.
Alternate array object(s) in which to put the result; if provided, it must have a shape that the inputs broadcast to. A tuple of arrays (possible only as a keyword argument) must have length equal to the number of outputs; use None for uninitialized outputs to be allocated by the ufunc.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
r will have the shape that the arrays in x broadcast to; if out is provided, it will be returned. If not, r will be allocated and may contain uninitialized values. If the function has more than one output, then the result will be a tuple of arrays.
The identity value.
The number of arguments.
The number of inputs.
The number of outputs.
The number of types.
Definition of the core elements a generalized ufunc operates on.
Returns a list with types grouped input->output.
__call__(*args, **kwargs)
Call self as a function.
accumulate(array[, axis, dtype, out])
Accumulate the result of applying the operator to all elements.
at(a, indices[, b])
Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'.
outer(A, B, /, **kwargs)
Apply the ufunc op to all pairs (a, b) with a in A and b in B.
reduce(array[, axis, dtype, out, keepdims, ...])
Reduces array's dimension by one, by applying ufunc along one axis.
reduceat(array, indices[, axis, dtype, out])
Performs a (local) reduce with specified slices over a single axis.


Unsigned integer type, compatible with C unsigned long.
'L'
numpy.uint64: 64-bit unsigned integer (0 to 18_446_744_073_709_551_615).
numpy.uintp: Unsigned integer large enough to fit pointer, compatible with C uintptr_t.


Alias for the unsigned integer types (one of numpy.ubyte, numpy.ushort, numpy.uintc, numpy.uint and numpy.ulonglong) with the specified number of bits.
Compatible with the C99 uint8_t, uint16_t, uint32_t, and uint64_t, respectively.


Unsigned integer type, compatible with C unsigned int.
'I'
numpy.uint32: 32-bit unsigned integer (0 to 4_294_967_295).


Alias for the unsigned integer type (one of numpy.ubyte, numpy.ushort, numpy.uintc, numpy.uint and np.ulonglong) that is the same size as a pointer.
Compatible with the C uintptr_t.
'P'


Signed integer type, compatible with C unsigned long long.
'Q'


Find the union of two arrays.
Return the unique, sorted array of values that are in either of the two input arrays.
Input arrays. They are flattened if they are not already 1D.
Unique, sorted union of the input arrays.
See also
Module with a number of other functions for performing set operations on arrays.
To find the union of more than two arrays, use functools.reduce:


Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:
Input array. Unless axis is specified, this will be flattened if it is not already 1-D.
If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array.
If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar.
If True, also return the number of times each unique item appears in ar.
New in version 1.9.0.
The axis to operate on. If None, ar will be flattened. If an integer, the subarrays indexed by the given axis will be flattened and treated as the elements of a 1-D array with the dimension of the given axis, see the notes for more details. Object arrays or structured arrays that contain objects are not supported if the axis kwarg is used. The default is None.
New in version 1.13.0.
The sorted unique values.
The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True.
The indices to reconstruct the original array from the unique array. Only provided if return_inverse is True.
The number of times each of the unique values comes up in the original array. Only provided if return_counts is True.
New in version 1.9.0.
See also
Module with a number of other functions for performing set operations on arrays.
Repeat elements of an array.
When an axis is specified the subarrays indexed by the axis are sorted. This is done by making the specified axis the first dimension of the array (move the axis to the first dimension to keep the order of the other axes) and then flattening the subarrays in C order. The flattened subarrays are then viewed as a structured type with each element given a label, with the effect that we end up with a 1-D array of structured types that can be treated in the same way as any other 1-D array. The result is that the flattened subarrays are sorted in lexicographic order starting with the first element.
Return the unique rows of a 2D array
Return the indices of the original array that give the unique values:
Reconstruct the input array from the unique values and inverse:
Reconstruct the input values from the unique values and counts:


Unpacks elements of a uint8 array into a binary-valued output array.
Each element of a represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified.
Input array.
The dimension over which bit-unpacking is done. None implies unpacking the flattened array.
The number of elements to unpack along axis, provided as a way of undoing the effect of packing a size that is not a multiple of eight. A non-negative number means to only unpack count bits. A negative number means to trim off that many bits from the end. None means to unpack the entire array (the default). Counts larger than the available number of bits will add zero padding to the output. Negative counts must not exceed the available number of bits.
New in version 1.17.0.
The order of the returned bits. ‘big’ will mimic bin(val), 3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1], ‘little’ will reverse the order to [1, 1, 0, 0, 0, 0, 0, 0]. Defaults to ‘big’.
New in version 1.17.0.
The elements are binary-valued (0 or 1).
See also
Packs the elements of a binary-valued array into bits in a uint8 array.


Converts a flat index or array of flat indices into a tuple of coordinate arrays.
An integer array whose elements are indices into the flattened version of an array of dimensions shape. Before version 1.6.0, this function accepted just one index value.
The shape of the array to use for unraveling indices.
Changed in version 1.16.0: Renamed from dims to shape.
Determines whether the indices should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.
New in version 1.6.0.
Each array in the tuple has the same shape as the indices array.
See also


Unwrap by taking the complement of large deltas with respect to the period.
This unwraps a signal p by changing elements which have an absolute difference from their predecessor of more than max(discont, period/2) to their period-complementary values.
For the default case where period is \(2\pi\) and discont is \(\pi\), this unwraps a radian phase p such that adjacent differences are never greater than \(\pi\) by adding \(2k\pi\) for some integer \(k\).
Input array.
Maximum discontinuity between values, default is period/2. Values below period/2 are treated as if they were period/2. To have an effect different from the default, discont should be larger than period/2.
Axis along which unwrap will operate, default is the last axis.
Size of the range over which the input wraps. By default, it is 2 pi.
New in version 1.21.0.
Output array.
See also
If the discontinuity in p is smaller than period/2, but larger than discont, no unwrapping is done because taking the complement would only make the discontinuity larger.


Unsigned integer type, compatible with C unsigned short.
'H'
numpy.uint16: 16-bit unsigned integer (0 to 65_535).


Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. The order of the powers is determined by the increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named for Alexandre- Theophile Vandermonde.
1-D input array.
Number of columns in the output. If N is not specified, a square array is returned (N = len(x)).
Order of the powers of the columns. If True, the powers increase from left to right, if False (the default) they are reversed.
New in version 1.9.0.
Vandermonde matrix. If increasing is False, the first column is x^(N-1), the second x^(N-2) and so forth. If increasing is True, the columns are x^0, x^1, ..., x^(N-1).
See also
The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector:


Compute the variance along the specified axis.
Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.
Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.
Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.
New in version 1.7.0.
If this is a tuple of ints, a variance is performed over multiple axes, instead of a single axis or all the axes as before.
Type to use in computing the variance. For arrays of integer type the default is float64; for arrays of float types it is the same as the array type.
Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary.
“Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of elements. By default ddof is zero.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the var method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
Elements to include in the variance. See reduce for details.
New in version 1.20.0.
If out=None, returns a new array containing the variance; otherwise, a reference to the output array is returned.
See also
The variance is the average of the squared deviations from the mean, i.e., var = mean(x), where x = abs(a - a.mean())**2.
The mean is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of a hypothetical infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables.
Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative.
For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue.
In single precision, var() can be inaccurate:
Computing the variance in float64 is more accurate:
Specifying a where argument:


Return the dot product of two vectors.
The vdot(a, b) function handles complex numbers differently than dot(a, b). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product.
Note that vdot handles multidimensional arrays differently than dot: it does not perform a matrix product, but flattens input arguments to 1-D vectors first. Consequently, it should only be used for vectors.
If a is complex the complex conjugate is taken before calculation of the dot product.
Second argument to the dot product.
Dot product of a and b. Can be an int, float, or complex depending on the types of a and b.
See also
Return the dot product without using the complex conjugate of the first argument.
Note that higher-dimensional arrays are flattened!


Generalized function class.
Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a single numpy array or a tuple of numpy arrays. The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy.
The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument.
A python function or method.
The output data type. It must be specified as either a string of typecode characters or a list of data type specifiers. There should be one data type specifier for each output.
The docstring for the function. If None, the docstring will be the pyfunc.__doc__.
Set of strings or integers representing the positional or keyword arguments for which the function will not be vectorized. These will be passed directly to pyfunc unmodified.
New in version 1.7.0.
If True, then cache the first function call that determines the number of outputs if otypes is not provided.
New in version 1.7.0.
Generalized universal function signature, e.g., (m,n),(n)->(m) for vectorized matrix-vector multiplication. If provided, pyfunc will be called with (and expected to return) arrays with shapes given by the size of corresponding core dimensions. By default, pyfunc is assumed to take scalars as input and output.
New in version 1.12.0.
Vectorized function.
See also
Takes an arbitrary Python function and returns a ufunc
The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.
If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.
The new keyword argument interface and excluded argument support further degrades performance.
Generalized Universal Function API
The docstring is taken from the input function to vectorize unless it is specified:
The output type is determined by evaluating the first element of the input, unless it is specified:
The excluded argument can be used to prevent vectorizing over certain arguments. This can be useful for array-like arguments of a fixed length such as the coefficients for a polynomial as in polyval:
Positional arguments may also be excluded by specifying their position:
The signature argument allows for vectorizing functions that act on non-scalar arrays of fixed length. For example, you can use it for a vectorized calculation of Pearson correlation coefficient and its p-value:
Or for a vectorized convolution:
__call__(*args, **kwargs)
Return arrays with the results of pyfunc broadcast (vectorized) over args and kwargs not in excluded.


Either an opaque sequence of bytes, or a structure.
Structured void scalars can only be constructed via extraction from Structured arrays:
'V'


Split an array into multiple sub-arrays vertically (row-wise).
Please refer to the split documentation. vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension.
See also
Split an array into multiple sub-arrays of equal size.
With a higher dimensional array the split is still along the first axis.


Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.
This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.
The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.
The array formed by stacking the given arrays, will be at least 2-D.
See also
Join a sequence of arrays along an existing axis.
Join a sequence of arrays along a new axis.
Assemble an nd-array from nested lists of blocks.
Stack arrays in sequence horizontally (column wise).
Stack arrays in sequence depth wise (along third axis).
Stack 1-D arrays as columns into a 2-D array.
Split an array into multiple sub-arrays vertically (row-wise).


Return elements chosen from x or y depending on condition.
Note
When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.
Where True, yield x, otherwise yield y.
Values from which to choose. x, y and condition need to be broadcastable to some shape.
An array with elements from x where condition is True, and elements from y elsewhere.
See also
The function that is called when x and y are omitted
If all the arrays are 1-D, where is equivalent to:
This can be used on multidimensional arrays too:
The shapes of x, y, and the condition are broadcast together:


Print the NumPy arrays in the given dictionary.
If there is no dictionary passed in or vardict is None then returns NumPy arrays in the globals() dictionary (all NumPy arrays in the namespace).
A dictionary possibly containing ndarrays. Default is globals().
Returns ‘None’.
Prints out the name, shape, bytes and type of all of the ndarrays present in vardict.


Return a new array of given shape and type, filled with zeros.
Shape of the new array, e.g., (2, 3) or 2.
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Array of zeros with the given shape, dtype, and order.
See also
Return an array of zeros with shape and type of input.
Return a new uninitialized array.
Return a new array setting values to one.
Return a new array of given shape filled with value.


Return an array of zeros with the same shape and type as a given array.
The shape and data-type of a define these same attributes of the returned array.
Overrides the data type of the result.
New in version 1.6.0.
Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible.
New in version 1.6.0.
If True, then the newly created array will use the sub-class type of a, otherwise it will be a base-class array. Defaults to True.
Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.
New in version 1.17.0.
Array of zeros with the same shape and type as a.
See also
Return an empty array with shape and type of input.
Return an array of ones with shape and type of input.
Return a new array with shape of input filled with value.
Return a new array setting values to zero.