In addition to the MaskedArray class, the numpy.ma module defines several constants.
The masked constant is a special case of MaskedArray, with a float datatype and a null shape. It is used to test whether a specific entry of a masked array is masked, or to mask one or several entries of a masked array:
Value indicating that a masked array has no invalid entry. nomask is used internally to speed up computations when the mask is not needed. It is represented internally as np.False_.
String used in lieu of missing data when a masked array is printed. By default, this string is '--'.


Return a new matrix of given shape and type, without initializing entries.
Shape of the empty matrix.
Desired output data-type.
Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
See also
empty, unlike zeros, does not set the matrix values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.


Return a matrix with ones on the diagonal and zeros elsewhere.
Number of rows in the output.
Number of columns in the output, defaults to n.
Index of the diagonal: 0 refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
Data-type of the returned matrix.
Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory.
New in version 1.14.0.
A n x M matrix where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.
See also
Equivalent array function.
Square identity matrix.


Returns the square identity matrix of given size.
Size of the returned identity matrix.
Data-type of the output. Defaults to float.
n x n matrix with its main diagonal set to one, and all other elements zero.
See also
Equivalent array function.
More general matrix identity function.


Matrix of ones.
Return a matrix of given shape and type, filled with ones.
Shape of the matrix
The desired data-type for the matrix, default is np.float64.
Whether to store matrix in C- or Fortran-contiguous order, default is ‘C’.
Matrix of ones of given shape, dtype, and order.
See also
Array of ones.
Zero matrix.
If shape has length one i.e. (N,), or is a scalar N, out becomes a single row matrix of shape (1,N).


Return a matrix of random values with given shape.
Create a matrix of the given shape and propagate it with random samples from a uniform distribution over [0, 1).
Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape.
The matrix of random values with shape given by *args.
See also
If the first argument is a tuple, other arguments are ignored:


Return a random matrix with data from the “standard normal” distribution.
randn generates a matrix filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1.
Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape.
A matrix of floating-point samples drawn from the standard normal distribution.
See also
For random samples from \(N(\mu, \sigma^2)\), use:
sigma * np.matlib.randn(...) + mu
Two-by-four matrix of samples from \(N(3, 6.25)\):


Repeat a 0-D to 2-D array or matrix MxN times.
The array or matrix to be repeated.
The number of times a is repeated along the first and second axes.
The result of repeating a.


Return a matrix of given shape and type, filled with zeros.
Shape of the matrix
The desired data-type for the matrix, default is float.
Whether to store the result in C- or Fortran-contiguous order, default is ‘C’.
Zero matrix of given shape, dtype, and order.
See also
Equivalent array function.
Return a matrix of ones.
If shape has length one i.e. (N,), or is a scalar N, out becomes a single row matrix of shape (1,N).


method
Test whether all matrix elements along a given axis evaluate to True.
See also
This is the same as ndarray.all, but it returns a matrix object.


method
Test whether any array element along a given axis evaluates to True.
Refer to numpy.any for full documentation.
Axis along which logical OR is performed
Output to existing array instead of creating new one, must have same shape as expected output
Returns a single bool if axis is None; otherwise, returns ndarray


method
Indexes of the maximum values along an axis.
Return the indexes of the first occurrences of the maximum values along the specified axis. If axis is None, the index is for the flattened matrix.
See also
This is the same as ndarray.argmax, but returns a matrix object where ndarray.argmax would return an ndarray.


method
Indexes of the minimum values along an axis.
Return the indexes of the first occurrences of the minimum values along the specified axis. If axis is None, the index is for the flattened matrix.
See also
This is the same as ndarray.argmin, but returns a matrix object where ndarray.argmin would return an ndarray.


method
Returns the indices that would partition this array.
Refer to numpy.argpartition for full documentation.
New in version 1.8.0.
See also
equivalent function


method
Returns the indices that would sort this array.
Refer to numpy.argsort for full documentation.
See also
equivalent function


method
Copy of the array, cast to a specified type.
Typecode or data-type to which the array is cast.
Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.


attribute
Base object if memory is from some other object.
The base of an array that owns its memory is None:
Slicing creates a view, whose memory is shared with x:


method
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.
If True, swap bytes in-place, default is False.
The byteswapped array. If inplace is True, this is a view to self.
Arrays of byte-strings are not swapped
but different representation in memory


method
Use an index array to construct a new array from a set of choices.
Refer to numpy.choose for full documentation.
See also
equivalent function


method
Return an array whose values are limited to [min, max]. One of max or min must be given.
Refer to numpy.clip for full documentation.
See also
equivalent function


method
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
See also
equivalent function


method
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See also
equivalent function


method
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See also
equivalent function


method
Return a copy of the array.
Controls the memory layout of the copy. ‘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. (Note that this function and numpy.copy are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)
See also
Similar function with different default behavior
This function is the preferred method for creating an array copy. The function numpy.copy is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.


attribute
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.
Possessing attributes data, shape, strides, etc.
See also
Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes):
A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0].
Note that unlike data_as, a reference will not be kept to the array: code like ctypes.c_void_p((a + b).ctypes.data) will result in a pointer to a deallocated array, and should be spelt (a + b).ctypes.data_as(ctypes.c_void_p)
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform (see c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
The returned pointer will keep a reference to the array.
Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short).
Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong).
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as_parameter attribute which will return an integer equal to the data attribute.


method
Return the cumulative product of the elements along the given axis.
Refer to numpy.cumprod for full documentation.
See also
equivalent function


method
Return the cumulative sum of the elements along the given axis.
Refer to numpy.cumsum for full documentation.
See also
equivalent function


attribute
Python buffer object pointing to the start of the array’s data.


method
Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.
Refer to numpy.diagonal for full documentation.
See also
equivalent function


method
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
A string naming the dump file.
Changed in version 1.17.0: pathlib.Path objects are now accepted.


method
Returns the pickle of the array as a string. pickle.loads will convert the string back to an array.


method
Fill the array with a scalar value.
All elements of a will be assigned this value.


attribute
Information about the memory layout of the array.
The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using lowercased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access.
Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true.
The data is in a single, C-style contiguous segment.
The data is in a single, Fortran-style contiguous segment.
The array owns the memory it uses or borrows it from another object.
The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.
The data and all elements are aligned appropriately for the hardware.
This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.
(Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array.
F_CONTIGUOUS and not C_CONTIGUOUS.
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
ALIGNED and WRITEABLE.
BEHAVED and C_CONTIGUOUS.
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.


attribute
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
See also
Return a copy of the array collapsed into one dimension.
An assignment example:


method
Return a flattened copy of the matrix.
All N elements of the matrix are placed into a single row.
‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. ‘A’ means to flatten in column-major order if m is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten m in the order the elements occur in memory. The default is ‘C’.
A copy of the matrix, flattened to a (1, N) matrix where N is the number of elements in the original matrix.
See also
Return a flattened array.
A 1-D flat iterator over the matrix.


method
Return self as an ndarray object.
Equivalent to np.asarray(self).
self as an ndarray


method
Return self as a flattened ndarray.
Equivalent to np.asarray(x).ravel()
self, 1-D, as an ndarray


method
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
The data type of the view. The dtype size of the view can not be larger than that of the array itself.
Number of bytes to skip before beginning the element view.
By choosing an offset of 8 bytes we can select the complex part of the array for our view:


method
Returns the (complex) conjugate transpose of self.
Equivalent to np.transpose(self) if self is real-valued.
complex conjugate transpose of self


method
Returns the (multiplicative) inverse of invertible self.
If self is non-singular, ret is such that ret * self == self * ret == np.matrix(np.eye(self[0,:].size)) all return True.
If self is singular.
See also


method
Returns the transpose of the matrix.
Does not conjugate! For the complex conjugate transpose, use .H.
The (non-conjugated) transpose of the matrix.
See also


method
Copy an element of an array to a standard Python scalar and return it.
A copy of the specified element of the array as a suitable Python scalar
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.


method
Insert scalar into an array (scalar is cast to array’s dtype, if possible)
There must be at least 1 argument, and define the last argument as item. Then, a.itemset(*args) is equivalent to but faster than a[args] = item. The item should be a scalar value and args must select a single item in the array a.
If one argument: a scalar, only used in case a is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple.
Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular location in an ndarray, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.


attribute
Length of one array element in bytes.


method
Return the maximum value along an axis.
See also
This is the same as ndarray.max, but returns a matrix object where ndarray.max would return an ndarray.


method
Returns the average of the matrix elements along the given axis.
Refer to numpy.mean for full documentation.
See also
Same as ndarray.mean except that, where that returns an ndarray, this returns a matrix object.


method
Return the minimum value along an axis.
See also
This is the same as ndarray.min, but returns a matrix object where ndarray.min would return an ndarray.


attribute
Total bytes consumed by the elements of the array.
Does not include memory consumed by non-element attributes of the array object.


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


method
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See also
equivalent function


method
Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.
New in version 1.8.0.
Element index to partition by. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once.
Deprecated since version 1.22.0: Passing booleans as index is deprecated.
Axis along which to sort. Default is -1, which means sort along the last axis.
Selection algorithm. Default is ‘introselect’.
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 to be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
See also
Return a parititioned copy of an array.
Indirect partition.
Full sort.
See np.partition for notes on the different algorithms.


method
Return the product of the array elements over the given axis.
Refer to prod for full documentation.
See also
Same as ndarray.prod, except, where that returns an ndarray, this returns a matrix object instead.


method
Peak-to-peak (maximum - minimum) value along the given axis.
Refer to numpy.ptp for full documentation.
See also
Same as ndarray.ptp, except, where that would return an ndarray object, this returns a matrix object.


method
Set a.flat[n] = values[n] for all n in indices.
Refer to numpy.put for full documentation.
See also
equivalent function


method
Return a flattened matrix.
Refer to numpy.ravel for more documentation.
The elements of m are read using this index order. ‘C’ means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if m is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used.
Return the matrix flattened to shape (1, N) where N is the number of elements in the original matrix. A copy is made only if necessary.
See also
returns a similar output matrix but always a copy
a flat iterator on the array.
related function which returns an ndarray


method
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See also
equivalent function


method
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See also
equivalent function
Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).


method
Change shape and size of array in-place.
Shape of resized array.
If False, reference count will not be checked. Default is True.
If a does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist.
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See also
Return a new array with the specified shape.
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:
Enlarging an array: as above, but missing entries are filled with zeros:
Referencing an array prevents resizing…
Unless refcheck is False:


method
Return a with each element rounded to the given number of decimals.
Refer to numpy.around for full documentation.
See also
equivalent function


method
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See also
equivalent function


method
Put a value into a specified place in a field defined by a data-type.
Place val into a’s field defined by dtype and beginning offset bytes into the field.
Value to be placed in field.
Data-type of the field in which to place val.
The number of bytes into the field at which to place val.
See also


method
Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)
Describes whether or not a can be written to.
Describes whether or not a is aligned properly for its type.
Describes whether or not a is a copy of another “base” array.
Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only four of which can be changed by the user: WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);
UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY;
WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array.
All flags can be accessed using the single (upper case) letter as well as the full name.


attribute
Number of elements in the array.
Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.
a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.


method
Sort an array in-place. Refer to numpy.sort for full documentation.
Axis along which to sort. Default is -1, which means sort along the last axis.
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. 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.
See also
Return a sorted copy of an array.
Indirect sort.
Indirect stable sort on multiple keys.
Find elements in sorted array.
Partial sort.
See numpy.sort for notes on the different sorting algorithms.
Use the order keyword to specify a field to use when sorting a structured array:


method
Return a possibly reshaped matrix.
Refer to numpy.squeeze for more documentation.
Selects a subset of the axes of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised.
The matrix, but as a (1, N) matrix if it had shape (N, 1).
See also
related function
If m has a single column then that column is returned as the single row of a matrix. Otherwise m is returned. The returned matrix is always either m itself or a view into m. Supplying an axis keyword argument will not affect the returned matrix but it may cause an error to be raised.


method
Return the standard deviation of the array elements along the given axis.
Refer to numpy.std for full documentation.
See also
This is the same as ndarray.std, except that where an ndarray would be returned, a matrix object is returned instead.


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
Returns the sum of the matrix elements, along the given axis.
Refer to numpy.sum for full documentation.
See also
This is the same as ndarray.sum, except that where an ndarray would be returned, a matrix object is returned instead.


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


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 matrix as a (possibly nested) list.
See ndarray.tolist for full documentation.
See also


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 matrix elements, along the given axis.
Refer to numpy.var for full documentation.
See also
This is the same as ndarray.var, except that where an ndarray would be returned, a matrix object is returned instead.


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
Write any changes in the array to the file on disk.
For further information, see memmap.
See also


Special values defined in numpy: nan, inf,
NaNs can be used as a poor-man’s mask (if you don’t care what the original value was)
Note: cannot use equality to test NaNs. E.g.:
Other related special value functions:
The following corresponds to the usual functions except that nans are excluded from the results:
The default is to 'warn' for invalid, divide, and overflow and 'ignore' for underflow. But this can be changed, and it can be set individually for different kinds of exceptions. The different behaviors are:
These behaviors can be set for all kinds of errors or specific ones:
Note that integer divide-by-zero is handled by the same machinery. These behaviors are set on a per-thread basis.
Only a survey of the choices. Little detail on how each works.
Plusses:
Minuses:
Lots of learning overhead:
Reference counting often difficult to get right.
Plusses:
Minuses:
Plusses:
good numpy support: arrays have all these in their ctypes attribute:
Minuses:
Plusses:
Minuses:
Plusses:
Minuses:
Plusses:
Minuses:
The clear choice to wrap Fortran code is f2py.
Pyfort is an older alternative, but not supported any longer. Fwrap is a newer project that looked promising but isn’t being developed any longer.


method
Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array.


method
Returns a view of array with the same type as self.


method
Return a parametrized wrapper around the ndarray type.
New in version 1.22.
A parametrized ndarray type.
See also
Type hinting generics in standard collections.
An ndarray alias generic w.r.t. its dtype.type.
This method is only available for python 3.9 and later.


method
Used if copy.copy is called on an array. Returns a copy of the array.
Equivalent to a.copy(order='K').


method
Used if copy.deepcopy is called on an array.


method
For unpickling.
The state argument must be a sequence that contains the following elements:
optional pickle version. If omitted defaults to 0.
a binary string with the data (or a list if ‘a’ is an object array)


method
Returns True if all elements evaluate to True.
Refer to numpy.all for full documentation.
See also
equivalent function


method
Returns True if any of the elements of a evaluate to True.
Refer to numpy.any for full documentation.
See also
equivalent function


method
Return indices of the maximum values along the given axis.
Refer to numpy.argmax for full documentation.
See also
equivalent function


method
Return indices of the minimum values along the given axis.
Refer to numpy.argmin for detailed documentation.
See also
equivalent function


method
Returns the indices that would partition this array.
Refer to numpy.argpartition for full documentation.
New in version 1.8.0.
See also
equivalent function


method
Returns the indices that would sort this array.
Refer to numpy.argsort for full documentation.
See also
equivalent function


method
Copy of the array, cast to a specified type.
Typecode or data-type to which the array is cast.
Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.


attribute
Base object if memory is from some other object.
The base of an array that owns its memory is None:
Slicing creates a view, whose memory is shared with x:


method
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.
If True, swap bytes in-place, default is False.
The byteswapped array. If inplace is True, this is a view to self.
Arrays of byte-strings are not swapped
but different representation in memory


method
Use an index array to construct a new array from a set of choices.
Refer to numpy.choose for full documentation.
See also
equivalent function


method
Return an array whose values are limited to [min, max]. One of max or min must be given.
Refer to numpy.clip for full documentation.
See also
equivalent function


method
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
See also
equivalent function


method
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See also
equivalent function


method
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See also
equivalent function


method
Return a copy of the array.
Controls the memory layout of the copy. ‘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. (Note that this function and numpy.copy are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)
See also
Similar function with different default behavior
This function is the preferred method for creating an array copy. The function numpy.copy is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.


attribute
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.
Possessing attributes data, shape, strides, etc.
See also
Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes):
A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0].
Note that unlike data_as, a reference will not be kept to the array: code like ctypes.c_void_p((a + b).ctypes.data) will result in a pointer to a deallocated array, and should be spelt (a + b).ctypes.data_as(ctypes.c_void_p)
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform (see c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
The returned pointer will keep a reference to the array.
Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short).
Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong).
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as_parameter attribute which will return an integer equal to the data attribute.


method
Return the cumulative product of the elements along the given axis.
Refer to numpy.cumprod for full documentation.
See also
equivalent function


method
Return the cumulative sum of the elements along the given axis.
Refer to numpy.cumsum for full documentation.
See also
equivalent function


attribute
Python buffer object pointing to the start of the array’s data.


method
Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.
Refer to numpy.diagonal for full documentation.
See also
equivalent function


attribute
Data-type of the array’s elements.
See also


method
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
A string naming the dump file.
Changed in version 1.17.0: pathlib.Path objects are now accepted.


method
Returns the pickle of the array as a string. pickle.loads will convert the string back to an array.


method
Fill the array with a scalar value.
All elements of a will be assigned this value.


attribute
Information about the memory layout of the array.
The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using lowercased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access.
Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true.
The data is in a single, C-style contiguous segment.
The data is in a single, Fortran-style contiguous segment.
The array owns the memory it uses or borrows it from another object.
The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.
The data and all elements are aligned appropriately for the hardware.
This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.
(Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array.
F_CONTIGUOUS and not C_CONTIGUOUS.
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
ALIGNED and WRITEABLE.
BEHAVED and C_CONTIGUOUS.
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.


attribute
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
See also
Return a copy of the array collapsed into one dimension.
An assignment example:


method
Return a copy of the array collapsed into one dimension.
‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
A copy of the input array, flattened to one dimension.
See also
Return a flattened array.
A 1-D flat iterator over the array.


method
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
The data type of the view. The dtype size of the view can not be larger than that of the array itself.
Number of bytes to skip before beginning the element view.
By choosing an offset of 8 bytes we can select the complex part of the array for our view:


attribute
The imaginary part of the array.


method
Copy an element of an array to a standard Python scalar and return it.
A copy of the specified element of the array as a suitable Python scalar
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.


method
Insert scalar into an array (scalar is cast to array’s dtype, if possible)
There must be at least 1 argument, and define the last argument as item. Then, a.itemset(*args) is equivalent to but faster than a[args] = item. The item should be a scalar value and args must select a single item in the array a.
If one argument: a scalar, only used in case a is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple.
Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular location in an ndarray, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.


attribute
Length of one array element in bytes.


method
Return the maximum along a given axis.
Refer to numpy.amax for full documentation.
See also
equivalent function


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


method
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See also
equivalent function


attribute
Total bytes consumed by the elements of the array.
Does not include memory consumed by non-element attributes of the array object.


You’ll need to know a bit of Python. For a refresher, see the Python tutorial.
To work the examples, you’ll need matplotlib installed in addition to NumPy.
Learner profile
This is a quick overview of arrays in NumPy. It demonstrates how n-dimensional (\(n>=2\)) arrays are represented and can be manipulated. In particular, if you don’t know how to apply common functions to n-dimensional arrays (without using for-loops), or if you want to understand axis and shape properties for n-dimensional arrays, this article might be of help.
Learning Objectives
After reading, you should be able to:
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.
For example, the array for the coordinates of a point in 3D space, [1, 2, 1], has one axis. That axis has 3 elements in it, so we say it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3.
NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality. The more important attributes of an ndarray object are:
the number of axes (dimensions) of the array.
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.
the total number of elements of the array. This is equal to the product of the elements of shape.
an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.
the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities.
There are several ways to create arrays.
For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences.
A frequent error consists in calling array with multiple arguments, rather than providing a single sequence as an argument.
array transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.
The type of the array can also be explicitly specified at creation time:
Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation.
The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64, but it can be specified via the key word argument dtype.
To create sequences of numbers, NumPy provides the arange function which is analogous to the Python built-in range, but returns an array.
When arange is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace that receives as an argument the number of elements that we want, instead of the step:
See also
array, zeros, zeros_like, ones, ones_like, empty, empty_like, arange, linspace, numpy.random.Generator.rand, numpy.random.Generator.randn, fromfunction, fromfile
When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout:
One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals as lists of matrices.
See below to get more details on reshape.
If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners:
To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions.
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.
Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The matrix product can be performed using the @ operator (in python >=3.5) or the dot function or method:
Some operations, such as += and *=, act in place to modify an existing array rather than create a new one.
When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting).
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class.
By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:
NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions” (ufunc). Within NumPy, these functions operate elementwise on an array, producing an array as output.
See also
all, any, apply_along_axis, argmax, argmin, argsort, average, bincount, ceil, clip, conj, corrcoef, cov, cross, cumprod, cumsum, diff, dot, floor, inner, invert, lexsort, max, maximum, mean, median, min, minimum, nonzero, outer, prod, re, round, sort, std, sum, trace, transpose, var, vdot, vectorize, where
One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.
Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas:
When fewer indices are provided than the number of axes, the missing indices are considered complete slices:
The expression within brackets in b[i] is treated as an i followed by as many instances of : as needed to represent the remaining axes. NumPy also allows you to write this using dots as b[i, ...].
The dots (...) represent as many colons as needed to produce a complete indexing tuple. For example, if x is an array with 5 axes, then
Iterating over multidimensional arrays is done with respect to the first axis:
However, if one wants to perform an operation on each element in the array, one can use the flat attribute which is an iterator over all the elements of the array:
See also
Indexing on ndarrays, Indexing routines (reference), newaxis, ndenumerate, indices
An array has a shape given by the number of elements along each axis:
The shape of an array can be changed with various commands. Note that the following three commands all return a modified array, but do not change the original array:
The order of the elements in the array resulting from ravel is normally “C-style”, that is, the rightmost index “changes the fastest”, so the element after a[0, 0] is a[0, 1]. If the array is reshaped to some other shape, again the array is treated as “C-style”. NumPy normally creates arrays stored in this order, so ravel will usually not need to copy its argument, but if the array was made by taking slices of another array or created with unusual options, it may need to be copied. The functions ravel and reshape can also be instructed, using an optional argument, to use FORTRAN-style arrays, in which the leftmost index changes the fastest.
The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself:
If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated:
See also
ndarray.shape, reshape, resize, ravel
Several arrays can be stacked together along different axes:
The function column_stack stacks 1D arrays as columns into a 2D array. It is equivalent to hstack only for 2D arrays:
On the other hand, the function row_stack is equivalent to vstack for any input arrays. In fact, row_stack is an alias for vstack:
In general, for arrays with more than two dimensions, hstack stacks along their second axes, vstack stacks along their first axes, and concatenate allows for an optional arguments giving the number of the axis along which the concatenation should happen.
Note
In complex cases, r_ and c_ are useful for creating arrays by stacking numbers along one axis. They allow the use of range literals :.
When used with arrays as arguments, r_ and c_ are similar to vstack and hstack in their default behavior, but allow for an optional argument giving the number of the axis along which to concatenate.
See also
hstack, vstack, column_stack, concatenate, c_, r_
Using hsplit, you can split an array along its horizontal axis, either by specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur:
vsplit splits along the vertical axis, and array_split allows one to specify along which axis to split.
When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. This is often a source of confusion for beginners. There are three cases:
Simple assignments make no copy of objects or their data.
Python passes mutable objects as references, so function calls make no copy.
Different array objects can share the same data. The view method creates a new array object that looks at the same data.
Slicing an array returns a view of it:
The copy method makes a complete copy of the array and its data.
Sometimes copy should be called after slicing if the original array is not required anymore. For example, suppose a is a huge intermediate result and the final result b only contains a small fraction of a, a deep copy should be made when constructing b with slicing:
If b = a[:100] is used instead, a is referenced by b and will persist in memory even if del a is executed.
Here is a list of some useful NumPy functions and methods names ordered in categories. See Routines for the full list.
arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r_, zeros, zeros_like
ndarray.astype, atleast_1d, atleast_2d, atleast_3d, mat
array_split, column_stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, ndarray.item, newaxis, ravel, repeat, reshape, resize, squeeze, swapaxes, take, transpose, vsplit, vstack
all, any, nonzero, where
argmax, argmin, argsort, max, min, ptp, searchsorted, sort
choose, compress, cumprod, cumsum, inner, ndarray.fill, imag, prod, put, putmask, real, sum
cov, mean, std, var
cross, dot, outer, linalg.svd, vdot
Broadcasting allows universal functions to deal in a meaningful way with inputs that do not have exactly the same shape.
The first rule of broadcasting is that if all input arrays do not have the same number of dimensions, a “1” will be repeatedly prepended to the shapes of the smaller arrays until all the arrays have the same number of dimensions.
The second rule of broadcasting ensures that arrays with a size of 1 along a particular dimension act as if they had the size of the array with the largest shape along that dimension. The value of the array element is assumed to be the same along that dimension for the “broadcast” array.
After application of the broadcasting rules, the sizes of all arrays must match. More details can be found in Broadcasting.
NumPy offers more indexing facilities than regular Python sequences. In addition to indexing by integers and slices, as we saw before, arrays can be indexed by arrays of integers and arrays of booleans.
When the indexed array a is multidimensional, a single array of indices refers to the first dimension of a. The following example shows this behavior by converting an image of labels into a color image using a palette.
We can also give indexes for more than one dimension. The arrays of indices for each dimension must have the same shape.
In Python, arr[i, j] is exactly the same as arr[(i, j)]—so we can put i and j in a tuple and then do the indexing with that.
However, we can not do this by putting i and j into an array, because this array will be interpreted as indexing the first dimension of a.
Another common use of indexing with arrays is the search of the maximum value of time-dependent series:
You can also use indexing with arrays as a target to assign to:
However, when the list of indices contains repetitions, the assignment is done several times, leaving behind the last value:
This is reasonable enough, but watch out if you want to use Python’s += construct, as it may not do what you expect:
Even though 0 occurs twice in the list of indices, the 0th element is only incremented once. This is because Python requires a += 1 to be equivalent to a = a + 1.
When we index arrays with arrays of (integer) indices we are providing the list of indices to pick. With boolean indices the approach is different; we explicitly choose which items in the array we want and which ones we don’t.
The most natural way one can think of for boolean indexing is to use boolean arrays that have the same shape as the original array:
This property can be very useful in assignments:
You can look at the following example to see how to use boolean indexing to generate an image of the Mandelbrot set:
The second way of indexing with booleans is more similar to integer indexing; for each dimension of the array we give a 1D boolean array selecting the slices we want:
Note that the length of the 1D boolean array must coincide with the length of the dimension (or axis) you want to slice. In the previous example, b1 has length 3 (the number of rows in a), and b2 (of length 4) is suitable to index the 2nd axis (columns) of a.
The ix_ function can be used to combine different vectors so as to obtain the result for each n-uplet. For example, if you want to compute all the a+b*c for all the triplets taken from each of the vectors a, b and c:
You could also implement the reduce as follows:
and then use it as:
The advantage of this version of reduce compared to the normal ufunc.reduce is that it makes use of the broadcasting rules in order to avoid creating an argument array the size of the output times the number of vectors.
See Structured arrays.
Here we give a list of short and useful tips.
To change the dimensions of an array, you can omit one of the sizes which will then be deduced automatically:
How do we construct a 2D array from a list of equally-sized row vectors? In MATLAB this is quite easy: if x and y are two vectors of the same length you only need do m=[x;y]. In NumPy this works via the functions column_stack, dstack, hstack and vstack, depending on the dimension in which the stacking is to be done. For example:
The logic behind those functions in more than two dimensions can be strange.
See also
NumPy for MATLAB users
The NumPy histogram function applied to an array returns a pair of vectors: the histogram of the array and a vector of the bin edges. Beware: matplotlib also has a function to build histograms (called hist, as in Matlab) that differs from the one in NumPy. The main difference is that pylab.hist plots the histogram automatically, while numpy.histogram only generates the data.
With Matplotlib >=3.4 you can also use plt.stairs(n, bins).


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


method
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See also
equivalent function


method
Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.
New in version 1.8.0.
Element index to partition by. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once.
Deprecated since version 1.22.0: Passing booleans as index is deprecated.
Axis along which to sort. Default is -1, which means sort along the last axis.
Selection algorithm. Default is ‘introselect’.
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 to be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
See also
Return a parititioned copy of an array.
Indirect partition.
Full sort.
See np.partition for notes on the different algorithms.


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


method
Peak to peak (maximum - minimum) value along a given axis.
Refer to numpy.ptp for full documentation.
See also
equivalent function


method
Set a.flat[n] = values[n] for all n in indices.
Refer to numpy.put for full documentation.
See also
equivalent function


method
Return a flattened array.
Refer to numpy.ravel for full documentation.
See also
equivalent function
a flat iterator on the array.


attribute
The real part of the array.
See also
equivalent function


method
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See also
equivalent function


method
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See also
equivalent function
Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).


method
Change shape and size of array in-place.
Shape of resized array.
If False, reference count will not be checked. Default is True.
If a does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist.
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See also
Return a new array with the specified shape.
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:
Enlarging an array: as above, but missing entries are filled with zeros:
Referencing an array prevents resizing…
Unless refcheck is False:


method
Return a with each element rounded to the given number of decimals.
Refer to numpy.around for full documentation.
See also
equivalent function


method
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See also
equivalent function


method
Put a value into a specified place in a field defined by a data-type.
Place val into a’s field defined by dtype and beginning offset bytes into the field.
Value to be placed in field.
Data-type of the field in which to place val.
The number of bytes into the field at which to place val.
See also


method
Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)
Describes whether or not a can be written to.
Describes whether or not a is aligned properly for its type.
Describes whether or not a is a copy of another “base” array.
Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only four of which can be changed by the user: WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);
UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY;
WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array.
All flags can be accessed using the single (upper case) letter as well as the full name.


attribute
Tuple of array dimensions.
The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.
See also
similar function
similar method


attribute
Number of elements in the array.
Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.
a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.


method
Sort an array in-place. Refer to numpy.sort for full documentation.
Axis along which to sort. Default is -1, which means sort along the last axis.
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. 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.
See also
Return a sorted copy of an array.
Indirect sort.
Indirect stable sort on multiple keys.
Find elements in sorted array.
Partial sort.
See numpy.sort for notes on the different sorting algorithms.
Use the order keyword to specify a field to use when sorting a structured array:


method
Remove axes of length one from a.
Refer to numpy.squeeze for full documentation.
See also
equivalent function


method
Returns the standard deviation of the array elements along given axis.
Refer to numpy.std for full documentation.
See also
equivalent function


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
Increment the multi-dimensional index by one.
This method is for backward compatibility only: do not use.
Deprecated since version 1.20.0: This method has been advised against since numpy 1.8.0, but only started emitting DeprecationWarning as of this version.


method
Resolve all writeback semantics in writeable operands.
New in version 1.15.0.
See also


method
Get a copy of the iterator in its current state.


method
Print the current state of the nditer instance and debug info to stdout.


method
When the “external_loop” was not used during construction, but is desired, this modifies the iterator to behave as if the flag was specified.


method
Check whether iterations are left, and perform a single internal iteration without returning the result. Used in the C-style pattern do-while pattern. For an example, see nditer.
Whether or not there are iterations left.


attribute
operands[Slice]
The array(s) to be iterated over. Valid only before the iterator is closed.


method
Removes axis i from the iterator. Requires that the flag “multi_index” be enabled.


method
When the “multi_index” flag was specified, this removes it, allowing the internal iteration structure to be optimized further.


method
Reset the iterator to its initial state.