Test element-wise for NaN and return result as a boolean array.
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
True where x is NaN, false otherwise. This is a scalar if x is a scalar.
See also
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.


Test element-wise for NaT (not a time) and return result as a boolean array.
New in version 1.13.0.
Input array with datetime or timedelta data type.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
True where x is NaT, false otherwise. This is a scalar if x is a scalar.
See also


Test element-wise for negative infinity, return result as bool array.
The input array.
A location into which the result is stored. If provided, it must have a shape that the input broadcasts to. If not provided or None, a freshly-allocated boolean array is returned.
A boolean array with the same dimensions as the input. If second argument is not supplied then a numpy boolean array is returned with values True where the corresponding element of the input is negative infinity and values False where the element of the input is not negative infinity.
If a second argument is supplied the result is stored there. If the type of that array is a numeric type the result is represented as zeros and ones, if the type is boolean then as False and True. The return value out is then a reference to that array.
See also
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).
Errors result if the second argument is also supplied when x is a scalar input, if first and second arguments have different shapes, or if the first argument has complex values.


Test element-wise for positive infinity, return result as bool array.
The input array.
A location into which the result is stored. If provided, it must have a shape that the input broadcasts to. If not provided or None, a freshly-allocated boolean array is returned.
A boolean array with the same dimensions as the input. If second argument is not supplied then a boolean array is returned with values True where the corresponding element of the input is positive infinity and values False where the element of the input is not positive infinity.
If a second argument is supplied the result is stored there. If the type of that array is a numeric type the result is represented as zeros and ones, if the type is boolean then as False and True. The return value out is then a reference to that array.
See also
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).
Errors result if the second argument is also supplied when x is a scalar input, if first and second arguments have different shapes, or if the first argument has complex values


Returns a bool array, where True if input element is real.
If element has complex type with zero complex part, the return value for that element is True.
Input array.
Boolean array of same shape as x.
See also
Return True if x is not a complex type.
isreal may behave unexpectedly for string or object arrays (see examples)
The function does not work on string arrays.
Returns True for all elements in input array of dtype=object even if any of the elements is complex.
isreal should not be used with object arrays


Return True if x is a not complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, isrealobj evaluates to False if the data type is complex.
The input can be of any type and shape.
The return value, False if x is of a complex type.
See also
The function is only meant for arrays with numerical values but it accepts all other objects. Since it assumes array input, the return value of other objects may be True.


Returns True if the type of element is a scalar type.
Input argument, can be of any type and shape.
True if element is a scalar type, False if it is not.
See also
Get the number of dimensions of an array
If you need a stricter way to identify a numerical scalar, use isinstance(x, numbers.Number), as that returns False for most non-numerical elements such as strings.
In most cases np.ndim(x) == 0 should be used instead of this function, as that will also return true for 0d arrays. This is how numpy overloads functions in the style of the dx arguments to gradient and the bins argument to histogram. Some key differences:
x
isscalar(x)
np.ndim(x) == 0
PEP 3141 numeric objects (including builtins)
True
True
builtin string and buffer objects
True
True
other builtin objects, like pathlib.Path, Exception, the result of re.compile
False
True
third-party objects like matplotlib.figure.Figure
False
True
zero-dimensional numpy arrays
False
True
other numpy arrays
False
False
list, tuple, and other sequence objects
False
False
NumPy supports PEP 3141 numbers:


Determines whether the given object represents a scalar data-type.
If rep is an instance of a scalar dtype, True is returned. If not, False is returned.
Boolean result of check whether rep is a scalar dtype.
See also
Strings are also a scalar type:


Determine if a class is a subclass of a second class.
issubclass_ is equivalent to the Python built-in issubclass, except that it returns False instead of raising a TypeError if one of the arguments is not a class.
Input class. True is returned if arg1 is a subclass of arg2.
Input class. If a tuple of classes, True is returned if arg1 is a subclass of any of the tuple elements.
Whether arg1 is a subclass of arg2 or not.
See also


Returns True if first argument is a typecode lower/equal in type hierarchy.
This is like the builtin issubclass, but for dtypes.
dtype or object coercible to one
See also
Overview of the numpy type hierarchy.
issubdtype can be used to check the type of arrays:
Similar types of different sizes are not subdtypes of each other:
but both are subtypes of floating:
For convenience, dtype-like objects are allowed too:


Determine if the first argument is a subclass of the second argument.
Data-types.
The result.
See also


Construct an open mesh from multiple sequences.
This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions.
Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].
Each sequence should be of integer or boolean type. Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in np.nonzero(boolean_sequence)).
N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh.
See also


Return the Kaiser window.
The Kaiser window is a taper formed by using a Bessel function.
Number of points in the output window. If zero or less, an empty array is returned.
Shape parameter for window.
The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).
See also
The Kaiser window is defined as
with
where \(I_0\) is the modified zeroth-order Bessel function.
The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based on Bessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence, or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative to total energy.
The Kaiser can approximate many other windows by varying the beta parameter.
beta
Window shape
0
Rectangular
5
Similar to a Hamming
6
Similar to a Hanning
8.6
Similar to a Blackman
A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned.
Most references to the Kaiser window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means “removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.
J. F. Kaiser, “Digital Filters” - Ch 7 in “Systems analysis by digital computer”, Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966).
E.R. Kanasewich, “Time Sequence Analysis in Geophysics”, The University of Alberta Press, 1975, pp. 177-178.
Wikipedia, “Window function”, https://en.wikipedia.org/wiki/Window_function
Plot the window and the frequency response:


Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first.
See also
The outer product
The function assumes that the number of dimensions of a and b are the same, if necessary prepending the smallest with ones. If a.shape = (r0,r1,..,rN) and b.shape = (s0,s1,...,sN), the Kronecker product has shape (r0*s0, r1*s1, ..., rN*SN). The elements are products of elements from a and b, organized explicitly by:
where:
In the common 2-D case (N=1), the block structure can be visualized:


Returns the lowest common multiple of |x1| and |x2|
Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
The lowest common multiple of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars.
See also
The greatest common divisor


Returns x1 * 2**x2, element-wise.
The mantissas x1 and twos exponents x2 are used to construct floating point numbers x1 * 2**x2.
Array of multipliers.
Array of twos exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The result of x1 * 2**x2. This is a scalar if both x1 and x2 are scalars.
See also
Return (y1, y2) from x = y1 * 2**y2, inverse to ldexp.
Complex dtypes are not supported, they will raise a TypeError.
ldexp is useful as the inverse of frexp, if used by itself it is more clear to simply use the expression x1 * 2**x2.


Shift the bits of an integer to the left.
Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying x1 by 2**x2.
Input values.
Number of zeros to append to x1. Has to be non-negative. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Return x1 with bits shifted x2 times to the left. This is a scalar if both x1 and x2 are scalars.
See also
Shift the bits of an integer to the right.
Return the binary representation of the input number as a string.
Note that the dtype of the second argument may change the dtype of the result and can lead to unexpected results in some cases (see Casting Rules):
The << operator can be used as a shorthand for np.left_shift on ndarrays.


Return the truth value of (x1 < x2) element-wise.
Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.
See also
The < operator can be used as a shorthand for np.less on ndarrays.


Return the truth value of (x1 <= x2) element-wise.
Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.
See also
The <= operator can be used as a shorthand for np.less_equal on ndarrays.


Perform an indirect stable sort using a sequence of keys.
Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, its rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.
The k different “columns” to be sorted. The last column (or row if keys is a 2D array) is the primary sort key.
Axis to be indirectly sorted. By default, sort over the last axis.
Array of indices that sort the keys along the specified axis.
See also
Indirect sort.
In-place sort.
Return a sorted copy of an array.
Sort names: first by surname, then by name.
Sort two columns of numbers:
Note that sorting is first according to the elements of a. Secondary sorting is according to the elements of b.
A normal argsort would have yielded:
Structured arrays are sorted lexically by argsort:


Set operations for arrays based on sorting.
For floating point arrays, inaccurate results may appear due to usual round-off and floating point comparison issues.
Speed could be gained in some operations by an implementation of numpy.sort, that can provide directly the permutation vectors, thus avoiding calls to numpy.argsort.
Original author: Robert Cimrman


Buffered iterator for big arrays.
Arrayterator creates a buffered iterator for reading big arrays in small contiguous blocks. The class is useful for objects stored in the file system. It allows iteration over the object without reading everything in memory; instead, small blocks are read and iterated over.
Arrayterator can be used with any object that supports multidimensional slices. This includes NumPy arrays, but also variables from Scientific.IO.NetCDF or pynetcdf for example.
The object to iterate over.
The buffer size. If buf_size is supplied, the maximum amount of data that will be read into memory is buf_size elements. Default is None, which will read as many element as possible into memory.
See also
Multidimensional array iterator.
Flat array iterator.
Create a memory-map to an array stored in a binary file on disk.
The algorithm works by first finding a “running dimension”, along which the blocks will be extracted. Given an array of dimensions (d1, d2, ..., dn), e.g. if buf_size is smaller than d1, the first dimension will be used. If, on the other hand, d1 < buf_size < d1*d2 the second dimension will be used, and so on. Blocks are extracted along this dimension, and when the last block is returned the process continues from the next dimension, until all elements have been read.
Now we can iterate over a_itor, and it will return arrays of size two. Since buf_size was smaller than any dimension, the first dimension will be iterated over first:
The shape of the array to be iterated over.
A 1-D flat iterator for Arrayterator objects.


Mixin defining all operator special methods using __array_ufunc__.
This class implements the special methods for almost all of Python’s builtin operators defined in the operator module, including comparisons (==, >, etc.) and arithmetic (+, *, -, etc.), by deferring to the __array_ufunc__ method, which subclasses must implement.
It is useful for writing classes that do not inherit from numpy.ndarray, but that should support arithmetic and numpy universal functions like arrays as described in A Mechanism for Overriding Ufuncs.
As an trivial example, consider this implementation of an ArrayLike class that simply wraps a NumPy array and ensures that the result of any arithmetic operation is also an ArrayLike object:
In interactions between ArrayLike objects and numbers or numpy arrays, the result is always another ArrayLike:
Note that unlike numpy.ndarray, ArrayLike does not allow operations with arbitrary, unrecognized types. This ensures that interactions with ArrayLike preserve a well-defined casting hierarchy.
New in version 1.13.


Parse and compare numpy version strings.
NumPy has the following versioning scheme (numbers given are examples; they can be > 9 in principle):
‘1.8.0b2.dev-f1234afa’, ‘1.8.1rc1.dev-f1234afa’, etc.
Comparing needs to be done against a valid version string or other NumpyVersion instance. Note that all development versions of the same (pre-)release compare equal.
New in version 1.9.0.
NumPy version string (np.__version__).


Structured arrays are ndarrays whose datatype is a composition of simpler datatypes organized as a sequence of named fields. For example,
Here x is a one-dimensional array of length two whose datatype is a structure with three fields: 1. A string of length 10 or less named ‘name’, 2. a 32-bit integer named ‘age’, and 3. a 32-bit float named ‘weight’.
If you index x at position 1 you get a structure:
You can access and modify individual fields of a structured array by indexing with the field name:
Structured datatypes are designed to be able to mimic ‘structs’ in the C language, and share a similar memory layout. They are meant for interfacing with C code and for low-level manipulation of structured buffers, for example for interpreting binary blobs. For these purposes they support specialized features such as subarrays, nested datatypes, and unions, and allow control over the memory layout of the structure.
Users looking to manipulate tabular data, such as stored in csv files, may find other pydata projects more suitable, such as xarray, pandas, or DataArray. These provide a high-level interface for tabular data analysis and are better optimized for that use. For instance, the C-struct-like memory layout of structured arrays in numpy can lead to poor cache behavior in comparison.
A structured datatype can be thought of as a sequence of bytes of a certain length (the structure’s itemsize) which is interpreted as a collection of fields. Each field has a name, a datatype, and a byte offset within the structure. The datatype of a field may be any numpy datatype including other structured datatypes, and it may also be a subarray data type which behaves like an ndarray of a specified shape. The offsets of the fields are arbitrary, and fields may even overlap. These offsets are usually determined automatically by numpy, but can also be specified.
Structured datatypes may be created using the function numpy.dtype. There are 4 alternative forms of specification which vary in flexibility and conciseness. These are further documented in the Data Type Objects reference page, and in summary they are:
A list of tuples, one tuple per field
Each tuple has the form (fieldname, datatype, shape) where shape is optional. fieldname is a string (or tuple if titles are used, see Field Titles below), datatype may be any object convertible to a datatype, and shape is a tuple of integers specifying subarray shape.
If fieldname is the empty string '', the field will be given a default name of the form f#, where # is the integer index of the field, counting from 0 from the left:
The byte offsets of the fields within the structure and the total structure itemsize are determined automatically.
A string of comma-separated dtype specifications
In this shorthand notation any of the string dtype specifications may be used in a string and separated by commas. The itemsize and byte offsets of the fields are determined automatically, and the field names are given the default names f0, f1, etc.
A dictionary of field parameter arrays
This is the most flexible form of specification since it allows control over the byte-offsets of the fields and the itemsize of the structure.
The dictionary has two required keys, ‘names’ and ‘formats’, and four optional keys, ‘offsets’, ‘itemsize’, ‘aligned’ and ‘titles’. The values for ‘names’ and ‘formats’ should respectively be a list of field names and a list of dtype specifications, of the same length. The optional ‘offsets’ value should be a list of integer byte-offsets, one for each field within the structure. If ‘offsets’ is not given the offsets are determined automatically. The optional ‘itemsize’ value should be an integer describing the total size in bytes of the dtype, which must be large enough to contain all the fields.
Offsets may be chosen such that the fields overlap, though this will mean that assigning to one field may clobber any overlapping field’s data. As an exception, fields of numpy.object_ type cannot overlap with other fields, because of the risk of clobbering the internal object pointer and then dereferencing it.
The optional ‘aligned’ value can be set to True to make the automatic offset computation use aligned offsets (see Automatic Byte Offsets and Alignment), as if the ‘align’ keyword argument of numpy.dtype had been set to True.
The optional ‘titles’ value should be a list of titles of the same length as ‘names’, see Field Titles below.
A dictionary of field names
The use of this form of specification is discouraged, but documented here because older numpy code may use it. The keys of the dictionary are the field names and the values are tuples specifying type and offset:
This form is discouraged because Python dictionaries do not preserve order in Python versions before Python 3.6, and the order of the fields in a structured dtype has meaning. Field Titles may be specified by using a 3-tuple, see below.
The list of field names of a structured datatype can be found in the names attribute of the dtype object:
The field names may be modified by assigning to the names attribute using a sequence of strings of the same length.
The dtype object also has a dictionary-like attribute, fields, whose keys are the field names (and Field Titles, see below) and whose values are tuples containing the dtype and byte offset of each field.
Both the names and fields attributes will equal None for unstructured arrays. The recommended way to test if a dtype is structured is with if dt.names is not None rather than if dt.names, to account for dtypes with 0 fields.
The string representation of a structured datatype is shown in the “list of tuples” form if possible, otherwise numpy falls back to using the more general dictionary form.
Numpy uses one of two methods to automatically determine the field byte offsets and the overall itemsize of a structured datatype, depending on whether align=True was specified as a keyword argument to numpy.dtype.
By default (align=False), numpy will pack the fields together such that each field starts at the byte offset the previous field ended, and the fields are contiguous in memory.
If align=True is set, numpy will pad the structure in the same way many C compilers would pad a C-struct. Aligned structures can give a performance improvement in some cases, at the cost of increased datatype size. Padding bytes are inserted between fields such that each field’s byte offset will be a multiple of that field’s alignment, which is usually equal to the field’s size in bytes for simple datatypes, see PyArray_Descr.alignment. The structure will also have trailing padding added so that its itemsize is a multiple of the largest field’s alignment.
Note that although almost all modern C compilers pad in this way by default, padding in C structs is C-implementation-dependent so this memory layout is not guaranteed to exactly match that of a corresponding struct in a C program. Some work may be needed, either on the numpy side or the C side, to obtain exact correspondence.
If offsets were specified using the optional offsets key in the dictionary-based dtype specification, setting align=True will check that each field’s offset is a multiple of its size and that the itemsize is a multiple of the largest field size, and raise an exception if not.
If the offsets of the fields and itemsize of a structured array satisfy the alignment conditions, the array will have the ALIGNED flag set.
A convenience function numpy.lib.recfunctions.repack_fields converts an aligned dtype or array to a packed one and vice versa. It takes either a dtype or structured ndarray as an argument, and returns a copy with fields re-packed, with or without padding bytes.
In addition to field names, fields may also have an associated title, an alternate name, which is sometimes used as an additional description or alias for the field. The title may be used to index an array, just like a field name.
To add titles when using the list-of-tuples form of dtype specification, the field name may be specified as a tuple of two strings instead of a single string, which will be the field’s title and field name respectively. For example:
When using the first form of dictionary-based specification, the titles may be supplied as an extra 'titles' key as described above. When using the second (discouraged) dictionary-based specification, the title can be supplied by providing a 3-element tuple (datatype, offset, title) instead of the usual 2-element tuple:
The dtype.fields dictionary will contain titles as keys, if any titles are used. This means effectively that a field with a title will be represented twice in the fields dictionary. The tuple values for these fields will also have a third element, the field title. Because of this, and because the names attribute preserves the field order while the fields attribute may not, it is recommended to iterate through the fields of a dtype using the names attribute of the dtype, which will not list titles, as in:
Structured datatypes are implemented in numpy to have base type numpy.void by default, but it is possible to interpret other numpy types as structured types using the (base_dtype, dtype) form of dtype specification described in Data Type Objects. Here, base_dtype is the desired underlying dtype, and fields and flags will be copied from dtype. This dtype is similar to a ‘union’ in C.
There are a number of ways to assign values to a structured array: Using python tuples, using scalar values, or using other structured arrays.
The simplest way to assign values to a structured array is using python tuples. Each assigned value should be a tuple of length equal to the number of fields in the array, and not a list or array as these will trigger numpy’s broadcasting rules. The tuple’s elements are assigned to the successive fields of the array, from left to right:
A scalar assigned to a structured element will be assigned to all fields. This happens when a scalar is assigned to a structured array, or when an unstructured array is assigned to a structured array:
Structured arrays can also be assigned to unstructured arrays, but only if the structured datatype has just a single field:
Assignment between two structured arrays occurs as if the source elements had been converted to tuples and then assigned to the destination elements. That is, the first field of the source array is assigned to the first field of the destination array, and the second field likewise, and so on, regardless of field names. Structured arrays with a different number of fields cannot be assigned to each other. Bytes of the destination structure which are not included in any of the fields are unaffected.
When assigning to fields which are subarrays, the assigned value will first be broadcast to the shape of the subarray.
Individual fields of a structured array may be accessed and modified by indexing the array with the field name.
The resulting array is a view into the original array. It shares the same memory locations and writing to the view will modify the original array.
This view has the same dtype and itemsize as the indexed field, so it is typically a non-structured array, except in the case of nested structures.
If the accessed field is a subarray, the dimensions of the subarray are appended to the shape of the result:
One can index and assign to a structured array with a multi-field index, where the index is a list of field names.
Warning
The behavior of multi-field indexes changed from Numpy 1.15 to Numpy 1.16.
The result of indexing with a multi-field index is a view into the original array, as follows:
Assignment to the view modifies the original array. The view’s fields will be in the order they were indexed. Note that unlike for single-field indexing, the dtype of the view has the same itemsize as the original array, and has fields at the same offsets as in the original array, and unindexed fields are merely missing.
Warning
In Numpy 1.15, indexing an array with a multi-field index returned a copy of the result above, but with fields packed together in memory as if passed through numpy.lib.recfunctions.repack_fields.
The new behavior as of Numpy 1.16 leads to extra “padding” bytes at the location of unindexed fields compared to 1.15. You will need to update any code which depends on the data having a “packed” layout. For instance code such as:
will need to be changed. This code has raised a FutureWarning since Numpy 1.12, and similar code has raised FutureWarning since 1.7.
In 1.16 a number of functions have been introduced in the numpy.lib.recfunctions module to help users account for this change. These are numpy.lib.recfunctions.repack_fields. numpy.lib.recfunctions.structured_to_unstructured, numpy.lib.recfunctions.unstructured_to_structured, numpy.lib.recfunctions.apply_along_fields, numpy.lib.recfunctions.assign_fields_by_name, and numpy.lib.recfunctions.require_fields.
The function numpy.lib.recfunctions.repack_fields can always be used to reproduce the old behavior, as it will return a packed copy of the structured array. The code above, for example, can be replaced with:
Furthermore, numpy now provides a new function numpy.lib.recfunctions.structured_to_unstructured which is a safer and more efficient alternative for users who wish to convert structured arrays to unstructured arrays, as the view above is often indeded to do. This function allows safe conversion to an unstructured type taking into account padding, often avoids a copy, and also casts the datatypes as needed, unlike the view. Code such as:
can be made safer by replacing with:
Assignment to an array with a multi-field index modifies the original array:
This obeys the structured array assignment rules described above. For example, this means that one can swap the values of two fields using appropriate multi-field indexes:
Indexing a single element of a structured array (with an integer index) returns a structured scalar:
Unlike other numpy scalars, structured scalars are mutable and act like views into the original array, such that modifying the scalar will modify the original array. Structured scalars also support access and assignment by field name:
Similarly to tuples, structured scalars can also be indexed with an integer:
Thus, tuples might be thought of as the native Python equivalent to numpy’s structured types, much like native python integers are the equivalent to numpy’s integer types. Structured scalars may be converted to a tuple by calling numpy.ndarray.item:
In order to prevent clobbering object pointers in fields of object type, numpy currently does not allow views of structured arrays containing objects.
If the dtypes of two void structured arrays are equal, testing the equality of the arrays will result in a boolean array with the dimensions of the original arrays, with elements set to True where all fields of the corresponding structures are equal. Structured dtypes are equal if the field names, dtypes and titles are the same, ignoring endianness, and the fields are in the same order:
Currently, if the dtypes of two void structured arrays are not equivalent the comparison fails, returning the scalar value False. This behavior is deprecated as of numpy 1.10 and will raise an error or perform elementwise comparison in the future.
The < and > operators always return False when comparing void structured arrays, and arithmetic and bitwise operations are not supported.
As an optional convenience numpy provides an ndarray subclass, numpy.recarray that allows access to fields of structured arrays by attribute instead of only by index. Record arrays use a special datatype, numpy.record, that allows field access by attribute on the structured scalars obtained from the array. The numpy.rec module provides functions for creating recarrays from various objects. Additional helper functions for creating and manipulating structured arrays can be found in numpy.lib.recfunctions.
The simplest way to create a record array is with numpy.rec.array:
numpy.rec.array can convert a wide variety of arguments into record arrays, including structured arrays:
The numpy.rec module provides a number of other convenience functions for creating record arrays, see record array creation routines.
A record array representation of a structured array can be obtained using the appropriate view:
For convenience, viewing an ndarray as type numpy.recarray will automatically convert to numpy.record datatype, so the dtype can be left out of the view:
To get back to a plain ndarray both the dtype and type must be reset. The following view does so, taking into account the unusual case that the recordarr was not a structured type:
Record array fields accessed by index or by attribute are returned as a record array if the field has a structured type but as a plain ndarray otherwise.
Note that if a field has the same name as an ndarray attribute, the ndarray attribute takes precedence. Such fields will be inaccessible by attribute but will still be accessible by index.
Collection of utilities to manipulate structured arrays.
Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience.
Add new fields to an existing array.
The names of the fields are given with the names arguments, the corresponding values with the data arguments. If a single field is appended, names, data and dtypes do not have to be lists but just values.
Input array to extend.
String or sequence of strings corresponding to the names of the new fields.
Array or sequence of arrays storing the fields to add to the base.
Datatype or sequence of datatypes. If None, the datatypes are estimated from the data.
Filling value used to pad missing data on the shorter arrays.
Whether to return a masked array or not.
Whether to return a recarray (MaskedRecords) or not.
Apply function ‘func’ as a reduction across fields of a structured array.
This is similar to apply_along_axis, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from numpy.result_type applied to the field’s dtypes.
Function to apply on the “field” dimension. This function must support an axis argument, like np.mean, np.sum, etc.
Structured array for which to apply func.
Result of the recution operation
Assigns values from one structured array to another by field name.
Normally in numpy >= 1.14, assignment of one structured array to another copies fields “by position”, meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name.
This function instead copies “by field name”, such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13.
The source and destination arrays during assignment.
If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified.
Return a new array with fields in drop_names dropped.
Nested fields are supported.
Changed in version 1.18.0: drop_fields returns an array with 0 fields if all fields are dropped, rather than returning None as it did previously.
Input array
String or sequence of strings corresponding to the names of the fields to drop.
Whether to return a masked array or not.
Whether to return a recarray or a mrecarray (asrecarray=True) or a plain ndarray or masked array with flexible dtype. The default is False.
Find the duplicates in a structured array along a given key
Input array
Name of the fields along which to check the duplicates. If None, the search is performed by records
Whether masked data should be discarded or considered as duplicates.
Whether to return the indices of the duplicated values.
Flatten a structured data-type description.
Returns a dictionary with fields indexing lists of their parent fields.
This function is used to simplify access to fields nested in other fields.
Input datatype
Last processed field name (used internally during recursion).
Dictionary of parent fields (used interbally during recursion).
Returns the field names of the input datatype as a tuple.
Input datatype
Returns the field names of the input datatype as a tuple. Nested structure are flattened beforehand.
Input datatype
Join arrays r1 and r2 on key key.
The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the key field cannot be found in the two input arrays. Neither r1 nor r2 should have any duplicates along key: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm.
A string or a sequence of strings corresponding to the fields used for comparison.
Structured arrays.
If ‘inner’, returns the elements common to both r1 and r2. If ‘outer’, returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If ‘leftouter’, returns the common elements and the elements of r1 not in r2.
String appended to the names of the fields of r1 that are present in r2 but absent of the key.
String appended to the names of the fields of r2 that are present in r1 but absent of the key.
Dictionary mapping field names to the corresponding default values.
Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray.
Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray.
Merge arrays field by field.
Sequence of arrays
Filling value used to pad missing data on the shorter arrays.
Whether to collapse nested fields.
Whether to return a masked array or not.
Whether to return a recarray (MaskedRecords) or not.
Without a mask, the missing value will be filled with something, depending on what its corresponding type:
Add new fields to an existing array.
The names of the fields are given with the names arguments, the corresponding values with the data arguments. If a single field is appended, names, data and dtypes do not have to be lists but just values.
Input array to extend.
String or sequence of strings corresponding to the names of the new fields.
Array or sequence of arrays storing the fields to add to the base.
Datatype or sequence of datatypes. If None, the datatypes are estimated from the data.
See also
Returns a new numpy.recarray with fields in drop_names dropped.
Join arrays r1 and r2 on keys. Alternative to join_by, that always returns a np.recarray.
See also
equivalent function
Fills fields from output with fields from input, with support for nested structures.
Input array.
Output array.
Rename the fields from a flexible-datatype ndarray or recarray.
Nested fields are supported.
Input array whose fields must be modified.
Dictionary mapping old field names to their new version.
Re-pack the fields of a structured array or dtype in memory.
The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap.
This method removes any overlaps and reorders the fields in memory so they have increasing byte offsets, and adds or removes padding bytes depending on the align option, which behaves like the align option to np.dtype.
If align=False, this method produces a “packed” memory layout in which each field starts at the byte the previous field ended, and any padding bytes are removed.
If align=True, this methods produces an “aligned” memory layout in which each field’s offset is a multiple of its alignment, and the total itemsize is a multiple of the largest alignment, by adding padding bytes as needed.
array or dtype for which to repack the fields.
If true, use an “aligned” memory layout, otherwise use a “packed” layout.
If True, also repack nested structures.
Copy of a with fields repacked, or a itself if no repacking was needed.
Casts a structured array to a new dtype using assignment by field-name.
This function assigns from the old to the new array by name, so the value of a field in the output array is the value of the field with the same name in the source array. This has the effect of creating a new ndarray containing only the fields “required” by the required_dtype.
If a field name in the required_dtype does not exist in the input array, that field is created and set to 0 in the output array.
array to cast
datatype for output array
array with the new dtype, with field values copied from the fields in the input array with the same name
Superposes arrays fields by fields
Sequence of input arrays.
Dictionary mapping field names to the corresponding default values.
Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray.
Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray.
Whether automatically cast the type of the field to the maximum.
Converts an n-D structured array into an (n+1)-D unstructured array.
The new array will have a new last dimension equal in size to the number of field-elements of the input array. If not supplied, the output datatype is determined from the numpy type promotion rules applied to all the field datatypes.
Nested fields, as well as each element of any subarray fields, all count as a single field-elements.
Structured array or dtype to convert. Cannot contain object datatype.
The dtype of the output unstructured array.
See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned.
See casting argument of ndarray.astype. Controls what kind of data casting may occur.
Unstructured array with one more dimension.
Converts an n-D unstructured array into an (n-1)-D structured array.
The last dimension of the input array is converted into a structure, with number of field-elements equal to the size of the last dimension of the input array. By default all output fields have the input array’s dtype, but an output structured dtype with an equal number of fields-elements can be supplied instead.
Nested fields, as well as each element of any subarray fields, all count towards the number of field-elements.
Unstructured array or dtype to convert.
The structured dtype of the output array
If dtype is not supplied, this specifies the field names for the output dtype, in order. The field dtypes will be the same as the input array.
Whether to create an aligned memory layout.
See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned.
See casting argument of ndarray.astype. Controls what kind of data casting may occur.
Structured array with fewer dimensions.


Apply function ‘func’ as a reduction across fields of a structured array.
This is similar to apply_along_axis, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from numpy.result_type applied to the field’s dtypes.
Function to apply on the “field” dimension. This function must support an axis argument, like np.mean, np.sum, etc.
Structured array for which to apply func.
Result of the recution operation


Assigns values from one structured array to another by field name.
Normally in numpy >= 1.14, assignment of one structured array to another copies fields “by position”, meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name.
This function instead copies “by field name”, such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13.
The source and destination arrays during assignment.
If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified.


Return a new array with fields in drop_names dropped.
Nested fields are supported.
Changed in version 1.18.0: drop_fields returns an array with 0 fields if all fields are dropped, rather than returning None as it did previously.
Input array
String or sequence of strings corresponding to the names of the fields to drop.
Whether to return a masked array or not.
Whether to return a recarray or a mrecarray (asrecarray=True) or a plain ndarray or masked array with flexible dtype. The default is False.


Find the duplicates in a structured array along a given key
Input array
Name of the fields along which to check the duplicates. If None, the search is performed by records
Whether masked data should be discarded or considered as duplicates.
Whether to return the indices of the duplicated values.


Flatten a structured data-type description.


Returns a dictionary with fields indexing lists of their parent fields.
This function is used to simplify access to fields nested in other fields.
Input datatype
Last processed field name (used internally during recursion).
Dictionary of parent fields (used interbally during recursion).


Returns the field names of the input datatype as a tuple.
Input datatype


Returns the field names of the input datatype as a tuple. Nested structure are flattened beforehand.
Input datatype


Join arrays r1 and r2 on key key.
The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the key field cannot be found in the two input arrays. Neither r1 nor r2 should have any duplicates along key: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm.
A string or a sequence of strings corresponding to the fields used for comparison.
Structured arrays.
If ‘inner’, returns the elements common to both r1 and r2. If ‘outer’, returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If ‘leftouter’, returns the common elements and the elements of r1 not in r2.
String appended to the names of the fields of r1 that are present in r2 but absent of the key.
String appended to the names of the fields of r2 that are present in r1 but absent of the key.
Dictionary mapping field names to the corresponding default values.
Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray.
Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray.


Merge arrays field by field.
Sequence of arrays
Filling value used to pad missing data on the shorter arrays.
Whether to collapse nested fields.
Whether to return a masked array or not.
Whether to return a recarray (MaskedRecords) or not.
Without a mask, the missing value will be filled with something, depending on what its corresponding type:


Add new fields to an existing array.
The names of the fields are given with the names arguments, the corresponding values with the data arguments. If a single field is appended, names, data and dtypes do not have to be lists but just values.
Input array to extend.
String or sequence of strings corresponding to the names of the new fields.
Array or sequence of arrays storing the fields to add to the base.
Datatype or sequence of datatypes. If None, the datatypes are estimated from the data.
See also


Returns a new numpy.recarray with fields in drop_names dropped.


Join arrays r1 and r2 on keys. Alternative to join_by, that always returns a np.recarray.
See also
equivalent function


Fills fields from output with fields from input, with support for nested structures.
Input array.
Output array.


Rename the fields from a flexible-datatype ndarray or recarray.
Nested fields are supported.
Input array whose fields must be modified.
Dictionary mapping old field names to their new version.


Re-pack the fields of a structured array or dtype in memory.
The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap.
This method removes any overlaps and reorders the fields in memory so they have increasing byte offsets, and adds or removes padding bytes depending on the align option, which behaves like the align option to np.dtype.
If align=False, this method produces a “packed” memory layout in which each field starts at the byte the previous field ended, and any padding bytes are removed.
If align=True, this methods produces an “aligned” memory layout in which each field’s offset is a multiple of its alignment, and the total itemsize is a multiple of the largest alignment, by adding padding bytes as needed.
array or dtype for which to repack the fields.
If true, use an “aligned” memory layout, otherwise use a “packed” layout.
If True, also repack nested structures.
Copy of a with fields repacked, or a itself if no repacking was needed.


Casts a structured array to a new dtype using assignment by field-name.
This function assigns from the old to the new array by name, so the value of a field in the output array is the value of the field with the same name in the source array. This has the effect of creating a new ndarray containing only the fields “required” by the required_dtype.
If a field name in the required_dtype does not exist in the input array, that field is created and set to 0 in the output array.
array to cast
datatype for output array
array with the new dtype, with field values copied from the fields in the input array with the same name


Superposes arrays fields by fields
Sequence of input arrays.
Dictionary mapping field names to the corresponding default values.
Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray.
Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray.
Whether automatically cast the type of the field to the maximum.


Converts an n-D structured array into an (n+1)-D unstructured array.
The new array will have a new last dimension equal in size to the number of field-elements of the input array. If not supplied, the output datatype is determined from the numpy type promotion rules applied to all the field datatypes.
Nested fields, as well as each element of any subarray fields, all count as a single field-elements.
Structured array or dtype to convert. Cannot contain object datatype.
The dtype of the output unstructured array.
See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned.
See casting argument of ndarray.astype. Controls what kind of data casting may occur.
Unstructured array with one more dimension.


Converts an n-D unstructured array into an (n-1)-D structured array.
The last dimension of the input array is converted into a structure, with number of field-elements equal to the size of the last dimension of the input array. By default all output fields have the input array’s dtype, but an output structured dtype with an equal number of fields-elements can be supplied instead.
Nested fields, as well as each element of any subarray fields, all count towards the number of field-elements.
Unstructured array or dtype to convert.
The structured dtype of the output array
If dtype is not supplied, this specifies the field names for the output dtype, in order. The field dtypes will be the same as the input array.
Whether to create an aligned memory layout.
See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned.
See casting argument of ndarray.astype. Controls what kind of data casting may occur.
Structured array with fewer dimensions.


Standard container-class for easy multiple-inheritance.
copy
tostring
byteswap
astype


Return evenly spaced numbers over a specified interval.
Returns num evenly spaced samples, calculated over the interval [start, stop].
The endpoint of the interval can optionally be excluded.
Changed in version 1.16.0: Non-scalar start and stop are now supported.
Changed in version 1.20.0: Values are rounded towards -inf instead of 0 when an integer dtype is specified. The old behavior can still be obtained with np.linspace(start, stop, num).astype(int)
The starting value of the sequence.
The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.
Number of samples to generate. Default is 50. Must be non-negative.
If True, stop is the last sample. Otherwise, it is not included. Default is True.
If True, return (samples, step), where step is the spacing between samples.
The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred dtype will never be an integer; float is chosen even if the arguments would produce an array of integers.
New in version 1.9.0.
The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
New in version 1.16.0.
There are num equally spaced samples in the closed interval [start, stop] or the half-open interval [start, stop) (depending on whether endpoint is True or False).
Only returned if retstep is True
Size of spacing between samples.
See also
Similar to linspace, but uses a step size (instead of the number of samples).
Similar to linspace, but with numbers spaced evenly on a log scale (a geometric progression).
Similar to geomspace, but with the end points specified as logarithms.
Graphical illustration:


Load arrays or pickled objects from .npy, .npz or pickled files.
Warning
Loading files that contain object arrays uses the pickle module, which is not secure against erroneous or maliciously constructed data. Consider passing allow_pickle=False to load data that is known not to contain object arrays for the safer handling of untrusted sources.
The file to read. File-like objects must support the seek() and read() methods. Pickled files require that the file-like object support the readline() method as well.
If not None, then memory-map the file, using the given mode (see numpy.memmap for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory.
Allow loading pickled object arrays stored in npy files. Reasons for disallowing pickles include security, as loading pickled data can execute arbitrary code. If pickles are disallowed, loading object arrays will fail. Default: False
Changed in version 1.16.3: Made default False in response to CVE-2019-6446.
Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. If fix_imports is True, pickle will try to map the old Python 2 names to the new names used in Python 3.
What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files in Python 3, which includes npy/npz files containing object arrays. Values other than ‘latin1’, ‘ASCII’, and ‘bytes’ are not allowed, as they can corrupt numerical data. Default: ‘ASCII’
Data stored in the file. For .npz files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors.
If the input file does not exist or cannot be read.
If allow_pickle=True, but the file cannot be loaded as a pickle.
The file contains an object array, but allow_pickle=False given.
See also
Create a memory-map to an array stored in a file on disk.
Create or load a memory-mapped .npy file.
If the file is a .npz file, the returned value supports the context manager protocol in a similar fashion to the open function:
The underlying file descriptor is closed when exiting the ‘with’ block.
Store data to disk, and load it again:
Store compressed data to disk, and load it again:
Mem-map the stored array, and then access the second row directly from disk:


Load data from a text file.
Each row in the text file must have the same number of values.
File, filename, list, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators must return bytes or strings. The strings in a list or produced by a generator are treated as lines.
Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type.
The characters or list of characters used to indicate the start of a comment. None implies no comments. For backwards compatibility, byte strings will be decoded as ‘latin1’. The default is ‘#’.
The string used to separate values. For backwards compatibility, byte strings will be decoded as ‘latin1’. The default is whitespace.
A dictionary mapping column number to a function that will parse the column string into the desired value. E.g., if column 0 is a date string: converters = {0: datestr2num}. Converters can also be used to provide a default value for missing data (but see also genfromtxt): converters = {3: lambda s: float(s.strip() or 0)}. Default: None.
Skip the first skiprows lines, including comments; default: 0.
Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read.
Changed in version 1.11.0: When a single column has to be read it is possible to use an integer instead of a tuple. E.g usecols = 3 reads the fourth column the same way as usecols = (3,) would.
If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(...). When used with a structured data-type, arrays are returned for each field. Default is False.
The returned array will have at least ndmin dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2.
New in version 1.6.0.
Encoding used to decode the inputfile. Does not apply to input streams. The special value ‘bytes’ enables backward compatibility workarounds that ensures you receive byte arrays as results if possible and passes ‘latin1’ encoded strings to converters. Override this value to receive unicode arrays and pass strings as input to converters. If set to None the system default is used. The default value is ‘bytes’.
New in version 1.14.0.
Read max_rows lines of content after skiprows lines. The default is to read all the lines.
New in version 1.16.0.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Data read from the text file.
See also
Load data with missing values handled as specified.
reads MATLAB data files
This function aims to be a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
New in version 1.10.0.
The strings produced by the Python float.hex method can be used as input for floats.
This example shows how converters can be used to convert a field with a trailing minus sign into a negative number.


Natural logarithm, element-wise.
The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.
Input value.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The natural logarithm of x, element-wise. This is a scalar if x is a scalar.
See also
Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = x. The convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard.
M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 67. https://personal.math.ubc.ca/~cbm/aands/page_67.htm
Wikipedia, “Logarithm”. https://en.wikipedia.org/wiki/Logarithm


Return the base 10 logarithm of the input array, element-wise.
Input values.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.
See also
Logarithm is a multivalued function: for each x there is an infinite number of z such that 10**z = x. The convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log10 always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log10 is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log10 handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard.
M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 67. https://personal.math.ubc.ca/~cbm/aands/page_67.htm
Wikipedia, “Logarithm”. https://en.wikipedia.org/wiki/Logarithm


Return the natural logarithm of one plus the input array, element-wise.
Calculates log(1 + x).
Input values.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.
See also
exp(x) - 1, the inverse of log1p.
For real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy.
Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = 1 + x. The convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log1p always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log1p is a complex analytical function that has a branch cut [-inf, -1] and is continuous from above on it. log1p handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard.
M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 67. https://personal.math.ubc.ca/~cbm/aands/page_67.htm
Wikipedia, “Logarithm”. https://en.wikipedia.org/wiki/Logarithm


Base-2 logarithm of x.
Input values.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Base-2 logarithm of x. This is a scalar if x is a scalar.
See also
New in version 1.3.0.
Logarithm is a multivalued function: for each x there is an infinite number of z such that 2**z = x. The convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log2 always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log2 is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log2 handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard.


Logarithm of the sum of exponentiations of the inputs.
Calculates log(exp(x1) + exp(x2)). This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the logarithm of the calculated probability is stored. This function allows adding probabilities stored in such a fashion.
Input values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Logarithm of exp(x1) + exp(x2). This is a scalar if both x1 and x2 are scalars.
See also
Logarithm of the sum of exponentiations of inputs in base 2.
New in version 1.3.0.


Logarithm of the sum of exponentiations of the inputs in base-2.
Calculates log2(2**x1 + 2**x2). This function is useful in machine learning when the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the base-2 logarithm of the calculated probability can be used instead. This function allows adding probabilities stored in such a fashion.
Input values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Base-2 logarithm of 2**x1 + 2**x2. This is a scalar if both x1 and x2 are scalars.
See also
Logarithm of the sum of exponentiations of the inputs.
New in version 1.3.0.


Compute the truth value of x1 AND x2 element-wise.
Input arrays. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.
See also
The & operator can be used as a shorthand for np.logical_and on boolean ndarrays.


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


Compute the truth value of x1 OR x2 element-wise.
Logical OR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Boolean result of the logical OR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.
See also
The | operator can be used as a shorthand for np.logical_or on boolean ndarrays.


Compute the truth value of x1 XOR x2, element-wise.
Logical XOR is applied to the elements of x1 and x2. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Boolean result of the logical XOR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.
See also
Simple example showing support of broadcasting


Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).
Changed in version 1.16.0: Non-scalar start and stop are now supported.
base ** start is the starting value of the sequence.
base ** stop is the final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.
Number of samples to generate. Default is 50.
If true, stop is the last sample. Otherwise, it is not included. Default is True.
The base of the log space. The step size between the elements in ln(samples) / ln(base) (or log_base(samples)) is uniform. Default is 10.0.
The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred type will never be an integer; float is chosen even if the arguments would produce an array of integers.
The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
New in version 1.16.0.
num samples, equally spaced on a log scale.
See also
Similar to linspace, with the step size specified instead of the number of samples. Note that, when used with a float endpoint, the endpoint may or may not be included.
Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space.
Similar to logspace, but with endpoints specified directly.
Logspace is equivalent to the code
Graphical illustration:


Extended-precision floating-point number type, compatible with C long double but not necessarily with IEEE 754 quadruple-precision.
'g'
numpy.longfloat
numpy.float128: 128-bit extended-precision floating-point number type.


Signed integer type, compatible with C long long.
'q'


Do a keyword search on docstrings.
A list of objects that matched the search is displayed, sorted by relevance. All given keywords need to be found in the docstring for it to be returned as a result, but the order does not matter.
String containing words to look for.
Name of module(s) whose docstrings to go through.
Whether to import sub-modules in packages. Default is True.
Whether to re-generate the docstring cache. Default is False.
File-like object to write the output to. If omitted, use a pager.
See also
Relevance is determined only roughly, by checking if the keywords occur in the function name, at the start of a docstring, etc.


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 '--'.


String used in lieu of missing data when a masked array is printed. By default, this string is '--'.


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_.


Diagnosing machine parameters.
Function that converts an integer or integer array to a float or float array. Default is float.
Function that converts a float or float array to an integer or integer array. Default is int.
Function that converts a float array to float. Default is float. Note that this does not seem to do anything useful in the current implementation.
Function that converts a single float to a string. Default is lambda v:'%24.16e' %v.
Title that is printed in the string representation of MachAr.
See also
Machine limits for floating point types.
Machine limits for integer types.
Press, Teukolsky, Vetterling and Flannery, “Numerical Recipes in C++,” 2nd ed, Cambridge University Press, 2002, p. 31.
Radix in which numbers are represented.
Number of base-ibeta digits in the floating point mantissa M.
Exponent of the smallest (most negative) power of ibeta that, added to 1.0, gives something different from 1.0
Floating-point number beta**machep (floating point precision)
Exponent of the smallest power of ibeta that, subtracted from 1.0, gives something different from 1.0.
Floating-point number beta**negep.
Number of bits in the exponent (including its sign and bias).
Smallest (most negative) power of ibeta consistent with there being no leading zeros in the mantissa.
Floating-point number beta**minexp (the smallest [in magnitude] positive floating point number with full precision).
Smallest (positive) power of ibeta that causes overflow.
(1-epsneg) * beta**maxexp (the largest [in magnitude] usable floating value).
In range(6), information on what kind of rounding is done in addition, and on how underflow is handled.
Number of ‘guard digits’ used when truncating the product of two mantissas to fit the representation.
Same as eps.
An alias for smallest_normal, kept for backwards compatibility.
Same as xmax.
- int(-log10(eps))
- 10**(-precision)
The smallest positive floating point number with 1 as leading bit in the mantissa following IEEE-754. Same as xmin.
The smallest positive floating point number with 0 as leading bit in the mantissa following IEEE-754.


Return the indices to access (n, n) arrays, given a masking function.
Assume mask_func is a function that, for a square array a of size (n, n) with a possible offset argument k, when called as mask_func(a, k) returns a new array with zeros in certain locations (functions like triu or tril do precisely this). Then this function returns the indices where the non-zero values would be located.
The returned indices will be valid to access arrays of shape (n, n).
A function whose call signature is similar to that of triu, tril. That is, mask_func(x, k) returns a boolean array, shaped like x. k is an optional argument to the function.
An optional argument which is passed through to mask_func. Functions like triu, tril take a second argument that is interpreted as an offset.
The n arrays of indices corresponding to the locations where mask_func(np.ones((n, n)), k) is True.
See also
New in version 1.4.0.
These are the indices that would allow you to access the upper triangular part of any 3x3 array:
For example, if a is a 3x3 array:
An offset can be passed also to the masking function. This gets us the indices starting on the first diagonal right of the main one:
with which we now extract only three elements:


Interpret the input as a matrix.
Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False).
Input data.
Data-type of the output matrix.
data interpreted as a matrix.


Matrix product of two arrays.
Input arrays, scalars not allowed.
A location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m). If not provided or None, a freshly-allocated array is returned.
For other keyword-only arguments, see the ufunc docs.
New in version 1.16: Now handles ufunc kwargs
The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.
If the last dimension of x1 is not the same size as the second-to-last dimension of x2.
If a scalar value is passed in.
See also
Complex-conjugating dot product.
Sum products over arbitrary axes.
Einstein summation convention.
alternative matrix product with different broadcasting rules.
The behavior depends on the arguments in the following way.
matmul differs from dot in two important ways:
Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature (n,k),(k,m)->(n,m):
The matmul function implements the semantics of the @ operator introduced in Python 3.5 following PEP 465.
For 2-D arrays it is the matrix product:
For 2-D mixed with 1-D, the result is the usual.
Broadcasting is conventional for stacks of arrays
Vector, vector returns the scalar inner product, but neither argument is complex-conjugated:
Scalar multiplication raises an error.
The @ operator can be used as a shorthand for np.matmul on ndarrays.
New in version 1.10.0.


Note
It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.
Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).
If data is a string, it is interpreted as a matrix with commas or spaces separating columns, and semicolons separating rows.
Data-type of the output matrix.
If data is already an ndarray, then this flag determines whether the data is copied (the default), or whether a view is constructed.
See also
Return self as an ndarray object.
Return self as a flattened ndarray.
Returns the (complex) conjugate transpose of self.
Returns the (multiplicative) inverse of invertible self.
Returns the transpose of the matrix.
Base object if memory is from some other object.
An object to simplify the interaction of the array with the ctypes module.
Python buffer object pointing to the start of the array’s data.
Data-type of the array’s elements.
Information about the memory layout of the array.
A 1-D iterator over the array.
The imaginary part of the array.
Length of one array element in bytes.
Total bytes consumed by the elements of the array.
Number of array dimensions.
The real part of the array.
Tuple of array dimensions.
Number of elements in the array.
Tuple of bytes to step in each dimension when traversing an array.
all([axis, out])
Test whether all matrix elements along a given axis evaluate to True.
any([axis, out])
Test whether any array element along a given axis evaluates to True.
argmax([axis, out])
Indexes of the maximum values along an axis.
argmin([axis, out])
Indexes of the minimum values along an axis.
argpartition(kth[, axis, kind, order])
Returns the indices that would partition this array.
argsort([axis, kind, order])
Returns the indices that would sort this array.
astype(dtype[, order, casting, subok, copy])
Copy of the array, cast to a specified type.
byteswap([inplace])
Swap the bytes of the array elements
choose(choices[, out, mode])
Use an index array to construct a new array from a set of choices.
clip([min, max, out])
Return an array whose values are limited to [min, max].
compress(condition[, axis, out])
Return selected slices of this array along given axis.
conj()
Complex-conjugate all elements.
conjugate()
Return the complex conjugate, element-wise.
copy([order])
Return a copy of the array.
cumprod([axis, dtype, out])
Return the cumulative product of the elements along the given axis.
cumsum([axis, dtype, out])
Return the cumulative sum of the elements along the given axis.
diagonal([offset, axis1, axis2])
Return specified diagonals.
dump(file)
Dump a pickle of the array to the specified file.
dumps()
Returns the pickle of the array as a string.
fill(value)
Fill the array with a scalar value.
flatten([order])
Return a flattened copy of the matrix.
getA()
Return self as an ndarray object.
getA1()
Return self as a flattened ndarray.
getH()
Returns the (complex) conjugate transpose of self.
getI()
Returns the (multiplicative) inverse of invertible self.
getT()
Returns the transpose of the matrix.
getfield(dtype[, offset])
Returns a field of the given array as a certain type.
item(*args)
Copy an element of an array to a standard Python scalar and return it.
itemset(*args)
Insert scalar into an array (scalar is cast to array's dtype, if possible)
max([axis, out])
Return the maximum value along an axis.
mean([axis, dtype, out])
Returns the average of the matrix elements along the given axis.
min([axis, out])
Return the minimum value along an axis.
newbyteorder([new_order])
Return the array with the same data viewed with a different byte order.
nonzero()
Return the indices of the elements that are non-zero.
partition(kth[, axis, kind, order])
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.
prod([axis, dtype, out])
Return the product of the array elements over the given axis.
ptp([axis, out])
Peak-to-peak (maximum - minimum) value along the given axis.
put(indices, values[, mode])
Set a.flat[n] = values[n] for all n in indices.
ravel([order])
Return a flattened matrix.
repeat(repeats[, axis])
Repeat elements of an array.
reshape(shape[, order])
Returns an array containing the same data with a new shape.
resize(new_shape[, refcheck])
Change shape and size of array in-place.
round([decimals, out])
Return a with each element rounded to the given number of decimals.
searchsorted(v[, side, sorter])
Find indices where elements of v should be inserted in a to maintain order.
setfield(val, dtype[, offset])
Put a value into a specified place in a field defined by a data-type.
setflags([write, align, uic])
Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
sort([axis, kind, order])
Sort an array in-place.
squeeze([axis])
Return a possibly reshaped matrix.
std([axis, dtype, out, ddof])
Return the standard deviation of the array elements along the given axis.
sum([axis, dtype, out])
Returns the sum of the matrix elements, along the given axis.
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
take(indices[, axis, out, mode])
Return an array formed from the elements of a at the given indices.
tobytes([order])
Construct Python bytes containing the raw data bytes in the array.
tofile(fid[, sep, format])
Write array to a file as text or binary (default).
tolist()
Return the matrix as a (possibly nested) list.
tostring([order])
A compatibility alias for tobytes, with exactly the same behavior.
trace([offset, axis1, axis2, dtype, out])
Return the sum along diagonals of the array.
transpose(*axes)
Returns a view of the array with axes transposed.
var([axis, dtype, out, ddof])
Returns the variance of the matrix elements, along the given axis.
view([dtype][, type])
New view of array with the same data.
dot


Element-wise maximum of array elements.
Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.
The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.
See also
Element-wise minimum of two arrays, propagates NaNs.
Element-wise maximum of two arrays, ignores NaNs.
The maximum value of an array along a given axis, propagates NaNs.
The maximum value of an array along a given axis, ignores NaNs.
The maximum is equivalent to np.where(x1 >= x2, x1, x2) when neither x1 nor x2 are nans, but it is faster and does proper broadcasting.


Return the scalar type of highest precision of the same kind as the input.
The input data type. This can be a dtype object or an object that is convertible to a dtype.
The highest precision data type of the same kind (dtype.kind) as t.
See also


Determine if two arrays might share memory
A return of True does not necessarily mean that the two arrays share any element. It just means that they might.
Only the memory bounds of a and b are checked by default.
Input arrays
Effort to spend on solving the overlap problem. See shares_memory for details. Default for may_share_memory is to do a bounds check.
See also


Compute the arithmetic mean along the specified axis.
Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.
Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.
New in version 1.7.0.
If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before.
Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.
Alternate output array in which to place the result. The default is None; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
Elements to include in the mean. See reduce for details.
New in version 1.20.0.
If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.
See also
Weighted average
The arithmetic mean is the sum of the elements along the axis divided by the number of elements.
Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-precision accumulator using the dtype keyword can alleviate this issue.
By default, float16 results are computed using float32 intermediates for extra precision.
In single precision, mean can be inaccurate:
Computing the mean in float64 is more accurate:
Specifying a where argument: >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]]) >>> np.mean(a) 12.0 >>> np.mean(a, where=[[True], [False], [False]]) 9.0


Compute the median along the specified axis.
Returns the median of the array elements.
Input array or object that can be converted to an array.
Axis or axes along which the medians are computed. The default is to compute the median along a flattened version of the array. A sequence of axes is supported since version 1.9.0.
Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.
If True, then allow use of memory of input array a for calculations. The input array will be modified by the call to median. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, but it will probably be fully or partially sorted. Default is False. If overwrite_input is True and a is not already an ndarray, an error will be raised.
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 arr.
New in version 1.9.0.
A new array holding the result. If the input contains integers or floats smaller than float64, then the output data-type is np.float64. Otherwise, the data-type of the output is the same as that of the input. If out is specified, that array is returned instead.
See also
Given a vector V of length N, the median of V is the middle value of a sorted copy of V, V_sorted - i e., V_sorted[(N-1)/2], when N is odd, and the average of the two middle values of V_sorted when N is even.