attribute
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:
A more detailed explanation of strides can be found in the “ndarray.rst” file in the NumPy reference guide.
See also
Imagine an array of 32-bit integers (each 4 bytes):
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be (20, 4).


method
Return the sum of the array elements over the given axis.
Refer to numpy.sum for full documentation.
See also
equivalent function


method
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See also
equivalent function


attribute
The transposed array.
Same as self.transpose().
See also


method
Return an array formed from the elements of a at the given indices.
Refer to numpy.take for full documentation.
See also
equivalent function


method
Construct Python bytes containing the raw data bytes in the array.
Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter.
New in version 1.9.0.
Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’.
Python bytes exhibiting a copy of a’s raw data.


method
Write array to a file as text or binary (default).
Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile().
An open file object, or a string containing a filename.
Changed in version 1.17.0: pathlib.Path objects are now accepted.
Separator between array items for text output. If “” (empty), a binary file is written, equivalent to file.write(a.tobytes()).
Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item.
This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.
When fid is a file object, array contents are directly written to the file, bypassing the file object’s write method. As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not support fileno() (e.g., BytesIO).


method
Return the array as an a.ndim-levels deep nested list of Python scalars.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function.
If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.
The possibly nested list of array elements.
The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision.
For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars:
Additionally, for a 2D array, tolist applies recursively:
The base case for this recursion is a 0D array:


method
A compatibility alias for tobytes, with exactly the same behavior.
Despite its name, it returns bytes not strs.
Deprecated since version 1.19.0.


method
Return the sum along diagonals of the array.
Refer to numpy.trace for full documentation.
See also
equivalent function


method
Returns a view of the array with axes transposed.
For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).
View of a, with axes suitably permuted.
See also
Equivalent function
Array property returning the array transposed.
Give a new shape to an array without changing its data.


method
Returns the variance of the array elements, along given axis.
Refer to numpy.var for full documentation.
See also
equivalent function


method
New view of array with the same data.
Note
Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_').
Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter).
Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.
a.view() is used two different ways:
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory.
For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results.
Viewing array data using a different type and dtype:
Creating a view on a structured array so it can be used in calculations
Making changes to the view changes the underlying array
Using a view to convert an array to a recarray:
Views share data:
Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.:


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.all.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.any.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.argmax.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.argmin.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.argsort.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.astype.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.byteswap.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.choose.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.clip.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.compress.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.conjugate.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.copy.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.cumprod.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.cumsum.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.diagonal.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.dump.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.dumps.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.fill.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.flatten.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.getfield.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.item.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.itemset.


attribute
The length of one element in bytes.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.max.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.mean.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.min.


attribute
The length of the scalar in bytes.


attribute
The number of array dimensions.


method
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
The new_order code can be any from the following:
Byte order to force; a value from the byte order specifications above. The default value (‘S’) results in swapping the current byte order.
New dtype object with the given change to the byte order.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.nonzero.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.prod.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.ptp.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.put.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.ravel.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.repeat.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.reshape.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.resize.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.round.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.searchsorted.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.setfield.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.setflags.


attribute
The number of elements in the gentype.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.sort.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.squeeze.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.std.


attribute
Tuple of bytes steps in each dimension.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.sum.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.swapaxes.


attribute
Scalar attribute identical to the corresponding array attribute.
Please see ndarray.T.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.take.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.tofile.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.tolist.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.tostring.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.trace.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.transpose.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.var.


method
Scalar method identical to the corresponding array attribute.
Please see ndarray.view.


1.22
December 31, 2021
This reference manual details functions, modules, and objects included in NumPy, describing what they are and what they do. For learning how to use NumPy, see the complete documentation.
Large parts of this manual originate from Travis E. Oliphant’s book Guide to NumPy (which generously entered Public Domain in August 2008). The reference documentation for many of the functions are written by numerous contributors and developers of NumPy.


In this chapter routine docstrings are presented, grouped by functionality. Many docstrings contain example code, which demonstrates basic usage of the routine. The examples assume that NumPy is imported with:
A convenient way to execute examples is the %doctest_mode mode of IPython, which allows for pasting of multi-line examples and preserves indentation.


Writing tests for the numpy.i SWIG interface file is a combinatorial headache. At present, 12 different data types are supported, each with 74 different argument signatures, for a total of 888 typemaps supported “out of the box”. Each of these typemaps, in turn, might require several unit tests in order to verify expected behavior for both proper and improper inputs. Currently, this results in more than 1,000 individual unit tests executed when make test is run in the numpy/tools/swig subdirectory.
To facilitate this many similar unit tests, some high-level programming techniques are employed, including C and SWIG macros, as well as Python inheritance. The purpose of this document is to describe the testing infrastructure employed to verify that the numpy.i typemaps are working as expected.
There are three independent testing frameworks supported, for one-, two-, and three-dimensional arrays respectively. For one-dimensional arrays, there are two C++ files, a header and a source, named:
that contain prototypes and code for a variety of functions that have one-dimensional arrays as function arguments. The file:
is a SWIG interface file that defines a python module Vector that wraps the functions in Vector.h while utilizing the typemaps in numpy.i to correctly handle the C arrays.
The Makefile calls swig to generate Vector.py and Vector_wrap.cxx, and also executes the setup.py script that compiles Vector_wrap.cxx and links together the extension module _Vector.so or _Vector.dylib, depending on the platform. This extension module and the proxy file Vector.py are both placed in a subdirectory under the build directory.
The actual testing takes place with a Python script named:
that uses the standard Python library module unittest, which performs several tests of each function defined in Vector.h for each data type supported.
Two-dimensional arrays are tested in exactly the same manner. The above description applies, but with Matrix substituted for Vector. For three-dimensional tests, substitute Tensor for Vector. For four-dimensional tests, substitute SuperTensor for Vector. For flat in-place array tests, substitute Flat for Vector. For the descriptions that follow, we will reference the Vector tests, but the same information applies to Matrix, Tensor and SuperTensor tests.
The command make test will ensure that all of the test software is built and then run all three test scripts.
Vector.h is a C++ header file that defines a C macro called TEST_FUNC_PROTOS that takes two arguments: TYPE, which is a data type name such as unsigned int; and SNAME, which is a short name for the same data type with no spaces, e.g. uint. This macro defines several function prototypes that have the prefix SNAME and have at least one argument that is an array of type TYPE. Those functions that have return arguments return a TYPE value.
TEST_FUNC_PROTOS is then implemented for all of the data types supported by numpy.i:
Vector.cxx is a C++ source file that implements compilable code for each of the function prototypes specified in Vector.h. It defines a C macro TEST_FUNCS that has the same arguments and works in the same way as TEST_FUNC_PROTOS does in Vector.h. TEST_FUNCS is implemented for each of the 12 data types as above.
Vector.i is a SWIG interface file that defines python module Vector. It follows the conventions for using numpy.i as described in this chapter. It defines a SWIG macro %apply_numpy_typemaps that has a single argument TYPE. It uses the SWIG directive %apply to apply the provided typemaps to the argument signatures found in Vector.h. This macro is then implemented for all of the data types supported by numpy.i. It then does a %include "Vector.h" to wrap all of the function prototypes in Vector.h using the typemaps in numpy.i.
After make is used to build the testing extension modules, testVector.py can be run to execute the tests. As with other scripts that use unittest to facilitate unit testing, testVector.py defines a class that inherits from unittest.TestCase:
However, this class is not run directly. Rather, it serves as a base class to several other python classes, each one specific to a particular data type. The VectorTestCase class stores two strings for typing information:
A string that matches one of the SNAME prefixes used in Vector.h and Vector.cxx. For example, "double".
A short (typically single-character) string that represents a data type in numpy and corresponds to self.typeStr. For example, if self.typeStr is "double", then self.typeCode should be "d".
Each test defined by the VectorTestCase class extracts the python function it is trying to test by accessing the Vector module’s dictionary:
In the case of double precision tests, this will return the python function Vector.doubleLength.
We then define a new test case class for each supported data type with a short definition such as:
Each of these 12 classes is collected into a unittest.TestSuite, which is then executed. Errors and failures are summed together and returned as the exit argument. Any non-zero result indicates that at least one test did not pass.


ptp(a[, axis, out, keepdims])
Range of values (maximum - minimum) along an axis.
percentile(a, q[, axis, out, ...])
Compute the q-th percentile of the data along the specified axis.
nanpercentile(a, q[, axis, out, ...])
Compute the qth percentile of the data along the specified axis, while ignoring nan values.
quantile(a, q[, axis, out, overwrite_input, ...])
Compute the q-th quantile of the data along the specified axis.
nanquantile(a, q[, axis, out, ...])
Compute the qth quantile of the data along the specified axis, while ignoring nan values.
median(a[, axis, out, overwrite_input, keepdims])
Compute the median along the specified axis.
average(a[, axis, weights, returned])
Compute the weighted average along the specified axis.
mean(a[, axis, dtype, out, keepdims, where])
Compute the arithmetic mean along the specified axis.
std(a[, axis, dtype, out, ddof, keepdims, where])
Compute the standard deviation along the specified axis.
var(a[, axis, dtype, out, ddof, keepdims, where])
Compute the variance along the specified axis.
nanmedian(a[, axis, out, overwrite_input, ...])
Compute the median along the specified axis, while ignoring NaNs.
nanmean(a[, axis, dtype, out, keepdims, where])
Compute the arithmetic mean along the specified axis, ignoring NaNs.
nanstd(a[, axis, dtype, out, ddof, ...])
Compute the standard deviation along the specified axis, while ignoring NaNs.
nanvar(a[, axis, dtype, out, ddof, ...])
Compute the variance along the specified axis, while ignoring NaNs.
corrcoef(x[, y, rowvar, bias, ddof, dtype])
Return Pearson product-moment correlation coefficients.
correlate(a, v[, mode])
Cross-correlation of two 1-dimensional sequences.
cov(m[, y, rowvar, bias, ddof, fweights, ...])
Estimate a covariance matrix, given data and weights.
histogram(a[, bins, range, normed, weights, ...])
Compute the histogram of a dataset.
histogram2d(x, y[, bins, range, normed, ...])
Compute the bi-dimensional histogram of two data samples.
histogramdd(sample[, bins, range, normed, ...])
Compute the multidimensional histogram of some data.
bincount(x, /[, weights, minlength])
Count number of occurrences of each value in array of non-negative ints.
histogram_bin_edges(a[, bins, range, weights])
Function to calculate only the edges of the bins used by the histogram function.
digitize(x, bins[, right])
Return the indices of the bins to which each value in input array belongs.


Raises an AssertionError if two objects are not equal up to desired tolerance.
The test is equivalent to allclose(actual, desired, rtol, atol) (note that allclose has different default values). It compares the difference between actual and desired to atol + rtol * abs(desired).
New in version 1.5.0.
Array obtained.
Array desired.
Relative tolerance.
Absolute tolerance.
If True, NaNs will compare equal.
The error message to be printed in case of failure.
If True, the conflicting values are appended to the error message.
If actual and desired are not equal up to specified precision.
See also


Raises an AssertionError if two items are not equal up to desired precision.
Note
It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons.
The test verifies that the elements of actual and desired satisfy.
abs(desired-actual) < 1.5 * 10**(-decimal)
That is a looser test than originally documented, but agrees with what the actual implementation in assert_array_almost_equal did up to rounding vagaries. An exception is raised at conflicting values. For ndarrays this delegates to assert_array_almost_equal
The object to check.
The expected object.
Desired precision, default is 7.
The error message to be printed in case of failure.
If True, the conflicting values are appended to the error message.
If actual and desired are not equal up to specified precision.
See also
Compare two array_like objects for equality with desired relative and/or absolute precision.


Raises an AssertionError if two items are not equal up to significant digits.
Note
It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons.
Given two numbers, check that they are approximately equal. Approximately equal is defined as the number of significant digits that agree.
The object to check.
The expected object.
Desired precision, default is 7.
The error message to be printed in case of failure.
If True, the conflicting values are appended to the error message.
If actual and desired are not equal up to specified precision.
See also
Compare two array_like objects for equality with desired relative and/or absolute precision.
the evaluated condition that raises the exception is


Raises an AssertionError if two objects are not equal up to desired precision.
Note
It is recommended to use one of assert_allclose, assert_array_almost_equal_nulp or assert_array_max_ulp instead of this function for more consistent floating point comparisons.
The test verifies identical shapes and that the elements of actual and desired satisfy.
abs(desired-actual) < 1.5 * 10**(-decimal)
That is a looser test than originally documented, but agrees with what the actual implementation did up to rounding vagaries. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
The actual object to check.
The desired, expected object.
Desired precision, default is 6.
The error message to be printed in case of failure.
If True, the conflicting values are appended to the error message.
If actual and desired are not equal up to specified precision.
See also
Compare two array_like objects for equality with desired relative and/or absolute precision.
the first assert does not raise an exception


Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude is variable.
Input arrays.
The maximum number of unit in the last place for tolerance (see Notes). Default is 1.
If the spacing between x and y for one or more elements is larger than nulp.
See also
Check that all items of arrays differ in at most N Units in the Last Place.
Return the distance between x and the nearest adjacent number.
An assertion is raised if the following condition is not met:


Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all elements of these objects are equal (but see the Notes for the special handling of a scalar). An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
The usual caution for verifying equality with floating point numbers is advised.
The actual object to check.
The desired, expected object.
The error message to be printed in case of failure.
If True, the conflicting values are appended to the error message.
If actual and desired objects are not equal.
See also
Compare two array_like objects for equality with desired relative and/or absolute precision.
When one of x and y is a scalar and the other is array_like, the function checks that each element of the array_like object is equal to the scalar.
The first assert does not raise an exception:
Assert fails with numerical imprecision with floats:
Use assert_allclose or one of the nulp (number of floating point values) functions for these cases instead:
As mentioned in the Notes section, assert_array_equal has special handling for scalars. Here the test checks that each value in x is 3:


Raises an AssertionError if two array_like objects are not ordered by less than.
Given two array_like objects, check that the shape is equal and all elements of the first object are strictly smaller than those of the second object. An exception is raised at shape mismatch or incorrectly ordered values. Shape mismatch does not raise if an object has zero dimension. In contrast to the standard usage in numpy, NaNs are compared, no assertion is raised if both objects have NaNs in the same positions.
The smaller object to check.
The larger object to compare.
The error message to be printed in case of failure.
If True, the conflicting values are appended to the error message.
If actual and desired objects are not equal.
See also
tests objects for equality
test objects for equality up to precision


Check that all items of arrays differ in at most N Units in the Last Place.
Input arrays to be compared.
The maximum number of units in the last place that elements of a and b can differ. Default is 1.
Data-type to convert a and b to if given. Default is None.
Array containing number of representable floating point numbers between items in a and b.
If one or more elements differ by more than maxulp.
See also
Compare two arrays relatively to their spacing.
For computing the ULP difference, this API does not differentiate between various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000 is zero).


Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), check that all elements of these objects are equal. An exception is raised at the first conflicting values.
When one of actual and desired is a scalar and the other is array_like, the function checks that each element of the array_like object is equal to the scalar.
This function handles NaN comparisons as if NaN was a “normal” number. That is, AssertionError is not raised if both objects have NaNs in the same positions. This is in contrast to the IEEE standard on NaNs, which says that NaN compared to anything must return False.
The object to check.
The expected object.
The error message to be printed in case of failure.
If True, the conflicting values are appended to the error message.
If actual and desired are not equal.
The following comparison does not raise an exception. There are NaNs in the inputs, but they are in the same positions.


Fail unless an exception of class exception_class is thrown by callable when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.
Alternatively, assert_raises can be used as a context manager:
is equivalent to


Fail unless an exception of class exception_class and with message that matches expected_regexp is thrown by callable when invoked with arguments args and keyword arguments kwargs.
Alternatively, can be used as a context manager like assert_raises.
Name of this function adheres to Python 3.2+ reference, but should work in all versions down to 2.6.
New in version 1.9.0.


Test if two strings are equal.
If the given strings are equal, assert_string_equal does nothing. If they are not equal, an AssertionError is raised, and the diff between the strings is shown.
The string to test for equality against the expected string.
The expected string.


Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when invoked with arguments args and keyword arguments kwargs. If a different type of warning is thrown, it will not be caught.
If called with all arguments other than the warning class omitted, may be used as a context manager:
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
New in version 1.4.0.
The class defining the warning that func is expected to throw.
Callable to test
Arguments for func.
Keyword arguments for func.


Deprecated since version 1.21: This decorator is retained for compatibility with the nose testing framework, which is being phased out. Please use the nose2 or pytest frameworks instead.
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning’s, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning.
Flag to determine whether to mark test as deprecated or not. If the condition is a callable, it is used at runtime to dynamically make the decision. Default is True.
The deprecated decorator itself.
New in version 1.4.0.


Deprecated since version 1.21: This decorator is retained for compatibility with the nose testing framework, which is being phased out. Please use the nose2 or pytest frameworks instead.
Make function raise KnownFailureException exception if given condition is true.
If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed.
Flag to determine whether to mark the decorated test as a known failure (if True) or not (if False).
Message to give on raising a KnownFailureException exception. Default is None.
Decorator, which, when applied to a function, causes KnownFailureException to be raised when fail_condition is True, and the function to be called normally otherwise.
The decorator itself is decorated with the nose.tools.make_decorator function in order to transmit function name, and various other metadata.


Deprecated since version 1.21: This decorator is retained for compatibility with the nose testing framework, which is being phased out. Please use the nose2 or pytest frameworks instead.
Signals to nose that this function is or is not a test.
If True, specifies that the decorated callable is a test. If False, specifies that the decorated callable is not a test. Default is True.
This decorator can’t use the nose namespace, because it can be called from a non-test module. See also istest and nottest in nose.tools.
setastest can be used in the following way:


Deprecated since version 1.21: This decorator is retained for compatibility with the nose testing framework, which is being phased out. Please use the nose2 or pytest frameworks instead.
Make function raise SkipTest exception if a given condition is true.
If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is actually executed.
Flag to determine whether to skip the decorated test.
Message to give on raising a SkipTest exception. Default is None.
Decorator which, when applied to a function, causes SkipTest to be raised when skip_condition is True, and the function to be called normally otherwise.
The decorator itself is decorated with the nose.tools.make_decorator function in order to transmit function name, and various other metadata.


Deprecated since version 1.21: This decorator is retained for compatibility with the nose testing framework, which is being phased out. Please use the nose2 or pytest frameworks instead.
Label a test as ‘slow’.
The exact definition of a slow test is obviously both subjective and hardware-dependent, but in general any individual test that requires more than a second or two should be labeled as slow (the whole suite consists of thousands of tests, so even a second is significant).
The test to label as slow.
The decorated test t.
The numpy.testing module includes import decorators as dec. A test can be decorated as slow like this:


Apply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of cls that are matched by the regular expression testmatch (testmatch.search(methodname)). Methods that are private, i.e. start with an underscore, are ignored.
Class whose methods to decorate.
Decorator to apply to methods
The regular expression. Default value is None, in which case the nose default (re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep)) is used. If testmatch is a string, it is compiled to a regular expression first.


Run a test module.
Equivalent to calling $ nosetests <argv> <file_to_run> from the command line
Path to test module, or None. By default, run the module from which this function is called.
Arguments to be passed to the nose test runner. argv[0] is ignored. All command line arguments accepted by nosetests will work. If it is the default value None, sys.argv is used.
New in version 1.9.0.
Adding the following:
at the end of a test module will run the tests when that module is called in the python interpreter.
Alternatively, calling:
from an interpreter will run all the test routine in ‘test_matlib.py’.


Run doctests found in the given file.
By default rundocs raises an AssertionError on failure.
The path to the file for which the doctests are run.
Whether to raise an AssertionError when a doctest fails. Default is True.
The doctests can be run by the user/developer by adding the doctests argument to the test() call. For example, to run all tests (including doctests) for numpy.lib:


method
Function decorator to apply certain suppressions to a whole function.


method
Add a new suppressing filter or apply it if the state is entered.
Warning class to filter
Regular expression matching the warning message.
Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules.
When added within a context, filters are only added inside the context and will be forgotten when the context is exited.


method
Append a new recording filter or apply it if the state is entered.
All warnings matching will be appended to the log attribute.
Warning class to filter
Regular expression matching the warning message.
Module to filter for. Note that the module (and its file) must match exactly and cannot be a submodule. This may make it unreliable for external modules.
A list which will be filled with all matched warnings.
When added within a context, filters are only added inside the context and will be forgotten when the context is exited.


method
Accumulate the result of applying the operator to all elements.
For a one-dimensional array, accumulate produces results equivalent to:
For example, add.accumulate() is equivalent to np.cumsum().
For a multi-dimensional array, accumulate is applied along only one axis (axis zero by default; see Examples below) so repeated use is necessary if one wants to accumulate over multiple axes.
The array to act on.
The axis along which to apply the accumulation; default is zero.
The data-type used to represent the intermediate results. Defaults to the data-type of the output array if such is provided, or the the data-type of the input array if no output array is provided.
A location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ufunc.__call__, if given as a keyword, this may be wrapped in a 1-element tuple.
Changed in version 1.13.0: Tuples are allowed for keyword argument.
The accumulated values. If out was supplied, r is a reference to out.
1-D array examples:
2-D array examples:
Accumulate along axis 0 (rows), down columns:
Accumulate along axis 1 (columns), through rows:


method
Performs unbuffered in place operation on operand ‘a’ for elements specified by ‘indices’. For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once. For example, a[[0,0]] += 1 will only increment the first element once because of buffering, whereas add.at(a, [0,0], 1) will increment the first element twice.
New in version 1.8.0.
The array to perform in place operation on.
Array like index object or slice object for indexing into first operand. If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects.
Second operand for ufuncs requiring two operands. Operand must be broadcastable over first operand after indexing or slicing.
Set items 0 and 1 to their negative values:
Increment items 0 and 1, and increment item 2 twice:
Add items 0 and 1 in first array to second array, and store results in first array:


attribute
The identity value.
Data attribute containing the identity element for the ufunc, if it has one. If it does not, the attribute value is None.


attribute
The number of arguments.
Data attribute containing the number of arguments the ufunc takes, including optional ones.
Typically this value will be one more than what you might expect because all ufuncs take the optional “out” argument.


attribute
The number of inputs.
Data attribute containing the number of arguments the ufunc treats as input.


attribute
The number of outputs.
Data attribute containing the number of arguments the ufunc treats as output.
Since all ufuncs can take output arguments, this will always be (at least) 1.


attribute
The number of types.
The number of numerical NumPy types - of which there are 18 total - on which the ufunc can operate.
See also


method
Apply the ufunc op to all pairs (a, b) with a in A and b in B.
Let M = A.ndim, N = B.ndim. Then the result, C, of op.outer(A, B) is an array of dimension M + N such that:
For A and B one-dimensional, this is equivalent to:
First array
Second array
Arguments to pass on to the ufunc. Typically dtype or out. See ufunc for a comprehensive overview of all available arguments.
Output array
See also
A less powerful version of np.multiply.outer that ravels all inputs to 1D. This exists primarily for compatibility with old code.
np.tensordot(a, b, axes=((), ())) and np.multiply.outer(a, b) behave same for all dimensions of a and b.
A multi-dimensional example:


method
Reduces array’s dimension by one, by applying ufunc along one axis.
Let \(array.shape = (N_0, ..., N_i, ..., N_{M-1})\). Then \(ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]\) = the result of iterating j over \(range(N_i)\), cumulatively applying ufunc to each \(array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]\). For a one-dimensional array, reduce produces results equivalent to:
For example, add.reduce() is equivalent to sum().
The array to act on.
Axis or axes along which a reduction is performed. The default (axis = 0) is perform a reduction over the first dimension of the input array. axis may be negative, in which case it counts from the last to the first axis.
New in version 1.7.0.
If this is None, a reduction is performed over all the axes. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
For operations which are either not commutative or not associative, doing a reduction over multiple axes is not well-defined. The ufuncs do not currently raise an exception in this case, but will likely do so in the future.
The type used to represent the intermediate results. Defaults to the data-type of the output array if this is provided, or the data-type of the input array if no output array is provided.
A location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ufunc.__call__, if given as a keyword, this may be wrapped in a 1-element tuple.
Changed in version 1.13.0: Tuples are allowed for keyword argument.
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 original array.
New in version 1.7.0.
The value with which to start the reduction. If the ufunc has no identity or the dtype is object, this defaults to None - otherwise it defaults to ufunc.identity. If None is given, the first element of the reduction is used, and an error is thrown if the reduction is empty.
New in version 1.15.0.
A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. Note that for ufuncs like minimum that do not have an identity defined, one has to pass in also initial.
New in version 1.17.0.
The reduced array. If out was supplied, r is a reference to it.
A multi-dimensional array example:
You can use the initial keyword argument to initialize the reduction with a different value, and where to select specific elements to include:
Allows reductions of empty arrays where they would normally fail, i.e. for ufuncs without an identity.


method
Performs a (local) reduce with specified slices over a single axis.
For i in range(len(indices)), reduceat computes ufunc.reduce(array[indices[i]:indices[i+1]]), which becomes the i-th generalized “row” parallel to axis in the final result (i.e., in a 2-D array, for example, if axis = 0, it becomes the i-th row, but if axis = 1, it becomes the i-th column). There are three exceptions to this:
The shape of the output depends on the size of indices, and may be larger than array (this happens if len(indices) > array.shape[axis]).
The array to act on.
Paired indices, comma separated (not colon), specifying slices to reduce.
The axis along which to apply the reduceat.
The type used to represent the intermediate results. Defaults to the data type of the output array if this is provided, or the data type of the input array if no output array is provided.
A location into which the result is stored. If not provided or None, a freshly-allocated array is returned. For consistency with ufunc.__call__, if given as a keyword, this may be wrapped in a 1-element tuple.
Changed in version 1.13.0: Tuples are allowed for keyword argument.
The reduced values. If out was supplied, r is a reference to out.
A descriptive example:
If array is 1-D, the function ufunc.accumulate(array) is the same as ufunc.reduceat(array, indices)[::2] where indices is range(len(array) - 1) with a zero placed in every other element: indices = zeros(2 * len(array) - 1), indices[1::2] = range(1, len(array)).
Don’t be fooled by this attribute’s name: reduceat(array) is not necessarily smaller than array.
To take the running sum of four successive values:
A 2-D example:


attribute
Definition of the core elements a generalized ufunc operates on.
The signature determines how the dimensions of each input/output array are split into core and loop dimensions:
Generalized ufuncs are used internally in many linalg functions, and in the testing suite; the examples below are taken from these. For ufuncs that operate on scalars, the signature is None, which is equivalent to ‘()’ for every argument.


attribute
Returns a list with types grouped input->output.
Data attribute listing the data-type “Domain-Range” groupings the ufunc can deliver. The data-types are given using the character codes.
See also


method
Return arrays with the results of pyfunc broadcast (vectorized) over args and kwargs not in excluded.


Note
This page describes the numpy-specific API for accessing the contents of a numpy array from other C extensions. PEP 3118 – The Revised Buffer Protocol introduces similar, standardized API to Python 2.6 and 3.0 for any extension module to use. Cython’s buffer array support uses the PEP 3118 API; see the Cython numpy tutorial. Cython provides a way to write code that supports the buffer protocol with Python versions older than 2.6 because it has a backward-compatible implementation utilizing the array interface described here.
3
The array interface (sometimes called array protocol) was created in 2005 as a means for array-like Python objects to re-use each other’s data buffers intelligently whenever possible. The homogeneous N-dimensional array interface is a default mechanism for objects to share N-dimensional array memory and information. The interface consists of a Python-side and a C-side using two attributes. Objects wishing to be considered an N-dimensional array in application code should support at least one of these attributes. Objects wishing to support an N-dimensional array in application code should look for at least one of these attributes and use the information provided appropriately.
This interface describes homogeneous arrays in the sense that each item of the array has the same “type”. This type can be very simple or it can be a quite arbitrary and complicated C-like structure.
There are two ways to use the interface: A Python side and a C-side. Both are separate attributes.
This approach to the interface consists of the object having an __array_interface__ attribute.
A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided.
The keys are:
Tuple whose elements are the array size in each dimension. Each entry is an integer (a Python int). Note that these integers could be larger than the platform int or long could hold (a Python int is a C long). It is up to the code using this attribute to handle this appropriately; either by raising an error when overflow is possible, or by using long long as the C type for the shapes.
A string providing the basic type of the homogeneous array The basic string format consists of 3 parts: a character describing the byteorder of the data (<: little-endian, >: big-endian, |: not-relevant), a character code giving the basic type of the array, and an integer providing the number of bytes the type uses.
The basic type character codes are:
t
Bit field (following integer gives the number of bits in the bit field).
b
Boolean (integer type where all values are only True or False)
i
Integer
u
Unsigned integer
f
Floating point
c
Complex floating point
m
Timedelta
M
Datetime
O
Object (i.e. the memory contains a pointer to PyObject)
S
String (fixed-length sequence of char)
U
Unicode (fixed-length sequence of Py_UNICODE)
V
Other (void * – each item is a fixed-size chunk of memory)
A list of tuples providing a more detailed description of the memory layout for each item in the homogeneous array. Each tuple in the list has two or three elements. Normally, this attribute would be used when typestr is V[0-9]+, but this is not a requirement. The only requirement is that the number of bytes represented in the typestr key is the same as the total number of bytes represented here. The idea is to support descriptions of C-like structs that make up array elements. The elements of each tuple in the list are
Default: [('', typestr)]
A 2-tuple whose first argument is an integer (a long integer if necessary) that points to the data-area storing the array contents. This pointer must point to the first element of data (in other words any offset is always ignored in this case). The second entry in the tuple is a read-only flag (true means the data area is read-only).
This attribute can also be an object exposing the buffer interface which will be used to share the data. If this key is not present (or returns None), then memory sharing will be done through the buffer interface of the object itself. In this case, the offset key can be used to indicate the start of the buffer. A reference to the object exposing the array interface must be stored by the new object if the memory area is to be secured.
Default: None
Either None to indicate a C-style contiguous array or a Tuple of strides which provides the number of bytes needed to jump to the next array element in the corresponding dimension. Each entry must be an integer (a Python int). As with shape, the values may be larger than can be represented by a C int or long; the calling code should handle this appropriately, either by raising an error, or by using long long in C. The default is None which implies a C-style contiguous memory buffer. In this model, the last dimension of the array varies the fastest. For example, the default strides tuple for an object whose array entries are 8 bytes long and whose shape is (10, 20, 30) would be (4800, 240, 8)
Default: None (C-style contiguous)
None or an object exposing the array interface. All elements of the mask array should be interpreted only as true or not true indicating which elements of this array are valid. The shape of this object should be “broadcastable” to the shape of the original array.
Default: None (All array values are valid)
An integer offset into the array data region. This can only be used when data is None or returns a buffer object.
Default: 0.
An integer showing the version of the interface (i.e. 3 for this version). Be careful not to use this to invalidate objects exposing future versions of the interface.
This approach to the array interface allows for faster access to an array using only one attribute lookup and a well-defined C-structure.
A PyCapsule whose pointer member contains a pointer to a filled PyArrayInterface structure. Memory for the structure is dynamically created and the PyCapsule is also created with an appropriate destructor so the retriever of this attribute simply has to apply Py_DECREF to the object returned by this attribute when it is finished. Also, either the data needs to be copied out, or a reference to the object exposing this attribute must be held to ensure the data is not freed. Objects exposing the __array_struct__ interface must also not reallocate their memory if other objects are referencing them.
The PyArrayInterface structure is defined in numpy/ndarrayobject.h as:
The flags member may consist of 5 bits showing how the data should be interpreted and one bit showing how the Interface should be interpreted. The data-bits are NPY_ARRAY_C_CONTIGUOUS (0x1), NPY_ARRAY_F_CONTIGUOUS (0x2), NPY_ARRAY_ALIGNED (0x100), NPY_ARRAY_NOTSWAPPED (0x200), and NPY_ARRAY_WRITEABLE (0x400). A final flag NPY_ARR_HAS_DESCR (0x800) indicates whether or not this structure has the arrdescr field. The field should not be accessed unless this flag is present.
New since June 16, 2006:
In the past most implementations used the desc member of the PyCObject (now PyCapsule) itself (do not confuse this with the “descr” member of the PyArrayInterface structure above — they are two separate things) to hold the pointer to the object exposing the interface. This is now an explicit part of the interface. Be sure to take a reference to the object and call PyCapsule_SetContext before returning the PyCapsule, and configure a destructor to decref this reference.
For clarity it is useful to provide some examples of the type description and corresponding __array_interface__ ‘descr’ entries. Thanks to Scott Gilbert for these examples:
In every case, the ‘descr’ key is optional, but of course provides more information which may be important for various applications:
It should be clear that any structured type could be described using this interface.
The version 2 interface was very similar. The differences were largely aesthetic. In particular:
The context member of the PyCapsule (formally the desc member of the PyCObject) returned from __array_struct__ was not specified. Usually, it was the object exposing the array (so that a reference to it could be kept and destroyed when the C-object was destroyed). It is now an explicit requirement that this field be used in some way to hold a reference to the owning object.
Note
Until August 2020, this said:
Now it must be a tuple whose first element is a string with “PyArrayInterface Version #” and whose second element is the object exposing the array.
This design was retracted almost immediately after it was proposed, in <https://mail.python.org/pipermail/numpy-discussion/2006-June/020995.html>. Despite 14 years of documentation to the contrary, at no point was it valid to assume that __array_interface__ capsules held this tuple content.
There was no __array_interface__ attribute instead all of the keys (except for version) in the __array_interface__ dictionary were their own attribute: Thus to obtain the Python-side information you had to access separately the attributes:


Binary serialization
A simple format for saving numpy arrays to disk with the full information about them.
The .npy format is the standard binary file format in NumPy for persisting a single arbitrary NumPy array on disk. The format stores all of the shape and dtype information necessary to reconstruct the array correctly even on another machine with a different architecture. The format is designed to be as simple as possible while achieving its limited goals.
The .npz format is the standard format for persisting multiple NumPy arrays on disk. A .npz file is a zip file containing multiple .npy files, one for each array.
Warning
Due to limitations in the interpretation of structured dtypes, dtypes with fields with empty names will have the names replaced by ‘f0’, ‘f1’, etc. Such arrays will not round-trip through the format entirely accurately. The data is intact; only the field names will differ. We are working on a fix for this. This fix will not require a change in the file format. The arrays with such structures can still be saved and restored, and the correct dtype may be restored by using the loadedarray.view(correct_dtype) method.
We recommend using the .npy and .npz extensions for files saved in this format. This is by no means a requirement; applications may wish to use these file formats but use an extension specific to the application. In the absence of an obvious alternative, however, we suggest using .npy and .npz.
The version numbering of these formats is independent of NumPy version numbering. If the format is upgraded, the code in numpy.io will still be able to read and write Version 1.0 files.
The first 6 bytes are a magic string: exactly \x93NUMPY.
The next 1 byte is an unsigned byte: the major version number of the file format, e.g. \x01.
The next 1 byte is an unsigned byte: the minor version number of the file format, e.g. \x00. Note: the version of the file format is not tied to the version of the numpy package.
The next 2 bytes form a little-endian unsigned short int: the length of the header data HEADER_LEN.
The next HEADER_LEN bytes form the header data describing the array’s format. It is an ASCII string which contains a Python literal expression of a dictionary. It is terminated by a newline (\n) and padded with spaces (\x20) to make the total of len(magic string) + 2 + len(length) + HEADER_LEN be evenly divisible by 64 for alignment purposes.
The dictionary contains three keys:
An object that can be passed as an argument to the numpy.dtype constructor to create the array’s dtype.
Whether the array data is Fortran-contiguous or not. Since Fortran-contiguous arrays are a common form of non-C-contiguity, we allow them to be written directly to disk for efficiency.
The shape of the array.
For repeatability and readability, the dictionary keys are sorted in alphabetic order. This is for convenience only. A writer SHOULD implement this if possible. A reader MUST NOT depend on this.
Following the header comes the array data. If the dtype contains Python objects (i.e. dtype.hasobject is True), then the data is a Python pickle of the array. Otherwise the data is the contiguous (either C- or Fortran-, depending on fortran_order) bytes of the array. Consumers can figure out the number of bytes by multiplying the number of elements given by the shape (noting that shape=() means there is 1 element) by dtype.itemsize.
The version 1.0 format only allowed the array header to have a total size of 65535 bytes. This can be exceeded by structured arrays with a large number of columns. The version 2.0 format extends the header size to 4 GiB. numpy.save will automatically save in 2.0 format if the data requires it, else it will always use the more compatible 1.0 format.
The description of the fourth element of the header therefore has become: “The next 4 bytes form a little-endian unsigned int: the length of the header data HEADER_LEN.”
This version replaces the ASCII string (which in practice was latin1) with a utf8-encoded string, so supports structured types with any unicode field names.
The .npy format, including motivation for creating it and a comparison of alternatives, is described in the “npy-format” NEP, however details have evolved with time and this document is more current.
descr_to_dtype(descr)
Returns a dtype based off the given description.
dtype_to_descr(dtype)
Get a serializable descriptor from the dtype.
header_data_from_array_1_0(array)
Get the dictionary of header metadata from a numpy.ndarray.
magic(major, minor)
Return the magic string for the given file format version.
open_memmap(filename[, mode, dtype, shape, ...])
Open a .npy file as a memory-mapped array.
read_array(fp[, allow_pickle, pickle_kwargs])
Read an array from an NPY file.
read_array_header_1_0(fp)
Read an array header from a filelike object using the 1.0 file format version.
read_array_header_2_0(fp)
Read an array header from a filelike object using the 2.0 file format version.
read_magic(fp)
Read the magic string to get the version of the file format.
write_array(fp, array[, version, ...])
Write an array to an NPY file, including a header.
write_array_header_1_0(fp, d)
Write the header for an array using the 1.0 format.
write_array_header_2_0(fp, d)
Write the header for an array using the 2.0 format.