Assemble an nd-array from nested lists of blocks.
Blocks in the innermost lists are concatenated (see concatenate) along the last dimension (-1), then these are concatenated along the second-last dimension (-2), and so on until the outermost list is reached.
Blocks can be of any dimension, but will not be broadcasted using the normal rules. Instead, leading axes of size 1 are inserted, to make block.ndim the same for all blocks. This is primarily useful for working with scalars, and means that code like np.block([v, 1]) is valid, where v.ndim == 1.
When the nested list is two levels deep, this allows block matrices to be constructed from their components.
New in version 1.13.0.
If passed a single ndarray or scalar (a nested list of depth 0), this is returned unmodified (and not copied).
Elements shapes must match along the appropriate axes (without broadcasting), but leading 1s will be prepended to the shape as necessary to make the dimensions match.
The array assembled from the given blocks.
The dimensionality of the output is equal to the greatest of: * the dimensionality of all the inputs * the depth to which the input list is nested
See also
Join a sequence of arrays along an existing axis.
Join a sequence of arrays along a new axis.
Stack arrays in sequence vertically (row wise).
Stack arrays in sequence horizontally (column wise).
Stack arrays in sequence depth wise (along third axis).
Stack 1-D arrays as columns into a 2-D array.
Split an array into multiple sub-arrays vertically (row-wise).
When called with only scalars, np.block is equivalent to an ndarray call. So np.block([[1, 2], [3, 4]]) is equivalent to np.array([[1, 2], [3, 4]]).
This function does not enforce that the blocks lie on a fixed grid. np.block([[a, b], [c, d]]) is not restricted to arrays of the form:
But is also allowed to produce, for some a, b, c, d:
Since concatenation happens along the last axis first, block is _not_ capable of producing the following directly:
Matlab’s “square bracket stacking”, [A, B, ...; p, q, ...], is equivalent to np.block([[A, B, ...], [p, q, ...]]).
The most common use of this function is to build a block matrix
With a list of depth 1, block can be used as hstack
With a list of depth 2, block can be used in place of vstack:
It can also be used in places of atleast_1d and atleast_2d


Build a matrix object from a string, nested sequence, or array.
Input data. If a string, variables in the current scope may be referenced by name.
A dictionary that replaces local operands in current frame. Ignored if obj is not a string or gdict is None.
A dictionary that replaces global operands in current frame. Ignored if obj is not a string.
Returns a matrix object, which is a specialized 2-D array.
See also
A generalization of this function for N-d arrays, that returns normal ndarrays.
All the following expressions construct the same block matrix:


Produce an object that mimics broadcasting.
Input parameters.
Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has shape and nd properties, and may be used as an iterator.
See also
Manually adding two vectors, using broadcasting:
Compare against built-in broadcasting:
current index in broadcasted result
tuple of iterators along self’s “components.”
Number of dimensions of broadcasted result.
Number of dimensions of broadcasted result.
Number of iterators possessed by the broadcasted result.
Shape of broadcasted result.
Total size of broadcasted result.
reset()
Reset the broadcasted result's iterator(s).


Broadcast any number of arrays against each other.
The arrays to broadcast.
If True, then sub-classes will be passed-through, otherwise the returned arrays will be forced to be a base-class array (default).
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. While you can set the writable flag True, writing to a single output value may end up changing more than one location in the output array.
Deprecated since version 1.17: The output is currently marked so that if written to, a deprecation warning will be emitted. A future version will set the writable flag False so writing to it will raise an error.
See also
Here is a useful idiom for getting contiguous copies instead of non-contiguous views.


Broadcast the input shapes into a single shape.
Learn more about broadcasting here.
New in version 1.20.0.
The shapes to be broadcast against each other.
Broadcasted shape.
If the shapes are not compatible and cannot be broadcast according to NumPy’s broadcasting rules.
See also


Broadcast an array to a new shape.
The array to broadcast.
The shape of the desired array. A single integer i is interpreted as (i,).
If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
If the array is not compatible with the new shape according to NumPy’s broadcasting rules.
See also
New in version 1.10.0.


Counts the number of valid days between begindates and enddates, not including the day of enddates.
If enddates specifies a date value that is earlier than the corresponding begindates date value, the count will be negative.
New in version 1.7.0.
The array of the first dates for counting.
The array of the end dates for counting, which are excluded from the count themselves.
A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like ‘1111100’; or a string like “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun
An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days.
A busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided.
If provided, this array is filled with the result.
An array with a shape from broadcasting begindates and enddates together, containing the number of valid days between the begin and end dates.
See also
An object that specifies a custom set of valid days.
Returns a boolean array indicating valid days.
Applies an offset counted in valid days.


First adjusts the date to fall on a valid day according to the roll rule, then applies offsets to the given dates counted in valid days.
New in version 1.7.0.
The array of dates to process.
The array of offsets, which is broadcast with dates.
How to treat dates that do not fall on a valid day. The default is ‘raise’.
A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like ‘1111100’; or a string like “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun
An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days.
A busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided.
If provided, this array is filled with the result.
An array with a shape from broadcasting dates and offsets together, containing the dates with offsets applied.
See also
An object that specifies a custom set of valid days.
Returns a boolean array indicating valid days.
Counts how many valid days are in a half-open date range.


A business day calendar object that efficiently stores information defining valid days for the busday family of functions.
The default valid days are Monday through Friday (“business days”). A busdaycalendar object can be specified with any set of weekly valid days, plus an optional “holiday” dates that always will be invalid.
Once a busdaycalendar object is created, the weekmask and holidays cannot be modified.
New in version 1.7.0.
A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like ‘1111100’; or a string like “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun
An array of dates to consider as invalid dates, no matter which weekday they fall upon. Holiday dates may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days.
A business day calendar object containing the specified weekmask and holidays values.
See also
Returns a boolean array indicating valid days.
Applies an offset counted in valid days.
Counts how many valid days are in a half-open date range.
A copy of the seven-element boolean mask indicating valid days.
A copy of the holiday array indicating additional invalid days.


Signed integer type, compatible with C char.
'b'
numpy.int8: 8-bit signed integer (-128 to 127).


Returns pointers to the end-points of an array.
Input array. It must conform to the Python-side of the array interface.
The first integer is the first byte of the array, the second integer is just past the last byte of the array. If a is not contiguous it will not use every byte between the (low, high) values.


A byte string.
When used in arrays, this type strips trailing null bytes.
'S'
numpy.string_


Translates slice objects to concatenation along the second axis.
This is short-hand for np.r_['-1,2,0', index expression], which is useful because of its common occurrence. In particular, arrays will be stacked along their last axis after being upgraded to at least 2-D with 1’s post-pended to the shape (column vectors made out of 1-D arrays).
See also
Stack 1-D arrays as columns into a 2-D array.
For more detailed documentation.


Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer.
Data type, scalar, or array to cast from.
Data type to cast to.
Controls what kind of data casting may occur.
True if cast can occur according to the casting rule.
See also
Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the maximum integer/float value converted.
Basic examples
Casting scalars
Array scalar checks the value, array does not
Using the casting rules


Return the cube-root of an array, element-wise.
New in version 1.10.0.
The values whose cube-roots are required.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
An array of the same shape as x, containing the cube cube-root of each element in x. If out was provided, y is a reference to it. This is a scalar if x is a scalar.


Complex number type composed of two double-precision floating-point numbers, compatible with Python complex.
'D'
numpy.cfloat
numpy.complex_
numpy.complex128: Complex number type composed of 2 64-bit-precision floating-point numbers.


Return the ceiling of the input, element-wise.
The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \(\lceil x \rceil\).
Input data.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.
See also


Provides a convenient view on arrays of string and unicode values.
Note
The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations.
Versus a regular NumPy array of type str or unicode, this class adds the following functionality:
chararrays should be created using numpy.char.array or numpy.char.asarray, rather than this constructor directly.
This constructor creates the array, using buffer (with offset and strides) if it is not None. If buffer is None, then constructs a new array with strides in “C order”, unless both len(shape) >= 2 and order='F', in which case strides is in “Fortran order”.
Shape of the array.
Length of each array element, in number of characters. Default is 1.
Are the array elements of type unicode (True) or string (False). Default is False.
Memory address of the start of the array data. Default is None, in which case a new array is created.
Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0.
Strides for the array (see ndarray.strides for full description). Default is None.
The order in which the array data is stored in memory: ‘C’ -> “row major” order (the default), ‘F’ -> “column major” (Fortran) order.
The transposed array.
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.
astype(dtype[, order, casting, subok, copy])
Copy of the array, cast to a specified type.
argsort([axis, kind, order])
Returns the indices that would sort this array.
copy([order])
Return a copy of the array.
count(sub[, start, end])
Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end].
decode([encoding, errors])
Calls str.decode element-wise.
dump(file)
Dump a pickle of the array to the specified file.
dumps()
Returns the pickle of the array as a string.
encode([encoding, errors])
Calls str.encode element-wise.
endswith(suffix[, start, end])
Returns a boolean array which is True where the string element in self ends with suffix, otherwise False.
expandtabs([tabsize])
Return a copy of each string element where all tab characters are replaced by one or more spaces.
fill(value)
Fill the array with a scalar value.
find(sub[, start, end])
For each element, return the lowest index in the string where substring sub is found.
flatten([order])
Return a copy of the array collapsed into one dimension.
getfield(dtype[, offset])
Returns a field of the given array as a certain type.
index(sub[, start, end])
Like find, but raises ValueError when the substring is not found.
isalnum()
Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise.
isalpha()
Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise.
isdecimal()
For each element in self, return True if there are only decimal characters in the element.
isdigit()
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise.
islower()
Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
isnumeric()
For each element in self, return True if there are only numeric characters in the element.
isspace()
Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise.
istitle()
Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise.
isupper()
Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise.
item(*args)
Copy an element of an array to a standard Python scalar and return it.
join(seq)
Return a string which is the concatenation of the strings in the sequence seq.
ljust(width[, fillchar])
Return an array with the elements of self left-justified in a string of length width.
lower()
Return an array with the elements of self converted to lowercase.
lstrip([chars])
For each element in self, return a copy with the leading characters removed.
nonzero()
Return the indices of the elements that are non-zero.
put(indices, values[, mode])
Set a.flat[n] = values[n] for all n in indices.
ravel([order])
Return a flattened array.
repeat(repeats[, axis])
Repeat elements of an array.
replace(old, new[, count])
For each element in self, return a copy of the string with all occurrences of substring old replaced by new.
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.
rfind(sub[, start, end])
For each element in self, return the highest index in the string where substring sub is found, such that sub is contained within [start, end].
rindex(sub[, start, end])
Like rfind, but raises ValueError when the substring sub is not found.
rjust(width[, fillchar])
Return an array with the elements of self right-justified in a string of length width.
rsplit([sep, maxsplit])
For each element in self, return a list of the words in the string, using sep as the delimiter string.
rstrip([chars])
For each element in self, return a copy with the trailing characters removed.
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.
split([sep, maxsplit])
For each element in self, return a list of the words in the string, using sep as the delimiter string.
splitlines([keepends])
For each element in self, return a list of the lines in the element, breaking at line boundaries.
squeeze([axis])
Remove axes of length one from a.
startswith(prefix[, start, end])
Returns a boolean array which is True where the string element in self starts with prefix, otherwise False.
strip([chars])
For each element in self, return a copy with the leading and trailing characters removed.
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
swapcase()
For each element in self, return a copy of the string with uppercase characters converted to lowercase and vice versa.
take(indices[, axis, out, mode])
Return an array formed from the elements of a at the given indices.
title()
For each element in self, return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase.
tofile(fid[, sep, format])
Write array to a file as text or binary (default).
tolist()
Return the array as an a.ndim-levels deep nested list of Python scalars.
tostring([order])
A compatibility alias for tobytes, with exactly the same behavior.
translate(table[, deletechars])
For each element in self, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table.
transpose(*axes)
Returns a view of the array with axes transposed.
upper()
Return an array with the elements of self converted to uppercase.
view([dtype][, type])
New view of array with the same data.
zfill(width)
Return the numeric string left-filled with zeros in a string of length width.


Construct an array from an index array and a list of arrays to choose from.
First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = numpy.lib.index_tricks):
np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)]).
But this omits some subtleties. Here is a fully general summary:
Given an “index” array (a) of integers and a sequence of n arrays (choices), a and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these Ba and Bchoices[i], i = 0,…,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape for each i. Then, a new array with shape Ba.shape is created as follows:
This array must contain integers in [0, n-1], where n is the number of choices, unless mode=wrap or mode=clip, in which cases any integers are permissible.
Choice arrays. a and all of the choices must be broadcastable to the same shape. If choices is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”.
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Note that out is always buffered if mode='raise'; use other modes for better performance.
Specifies how indices outside [0, n-1] will be treated:
The merged result.
If a and each choice array are not all broadcastable to the same shape.
See also
equivalent method
Preferable if choices is an array
To reduce the chance of misinterpretation, even though the following “abuse” is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple.
A couple examples illustrating how choose broadcasts:


Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.
Equivalent to but faster than np.minimum(a_max, np.maximum(a, a_min)).
No check is performed to ensure a_min < a_max.
Array containing elements to clip.
Minimum and maximum value. If None, clipping is not performed on the corresponding edge. Only one of a_min and a_max may be None. Both are broadcast against a.
The results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved.
For other keyword-only arguments, see the ufunc docs.
New in version 1.17.0.
An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.
See also
When a_min is greater than a_max, clip returns an array in which all values are equal to a_max, as shown in the second example.


Complex number type composed of two extended-precision floating-point numbers.
'G'
numpy.clongfloat
numpy.longcomplex
numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.


Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack. 1-D arrays are turned into 2-D columns first.
Arrays to stack. All of them must have the same first dimension.
The array formed by stacking the given arrays.
See also


Return a scalar type which is common to the input arrays.
The return type will always be an inexact (i.e. floating point) scalar type, even if all the arrays are integer arrays. If one of the inputs is an integer array, the minimum precision type that is returned is a 64-bit floating point dtype.
All input arrays except int64 and uint64 can be safely cast to the returned dtype without loss of information.
Input arrays.
Data type code.
See also


Alias for numpy.clongdouble, named after its size in bits. The existence of these aliases depends on the platform.


Return selected slices of an array along given axis.
When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. When working on a 1-D array, compress is equivalent to extract.
Array that selects which entries to return. If len(condition) is less than the size of a along the given axis, then output is truncated to the length of the condition array.
Array from which to extract a part.
Axis along which to take slices. If None (default), work on the flattened array.
Output array. Its type is preserved and it must be of the right shape to hold the output.
A copy of a without the slices along axis for which condition is false.
See also
Equivalent method in ndarray
Equivalent method when working on 1-D arrays
Working on the flattened array does not return slices along an axis but selects elements.


Join a sequence of arrays along an existing axis.
The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.
If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.
If provided, the destination array will have this dtype. Cannot be provided together with out.
New in version 1.20.0.
Controls what kind of data casting may occur. Defaults to ‘same_kind’.
New in version 1.20.0.
The concatenated array.
See also
Concatenate function that preserves input masks.
Split an array into multiple sub-arrays of equal or near-equal size.
Split array into a list of multiple sub-arrays of equal size.
Split array into multiple sub-arrays horizontally (column wise).
Split array into multiple sub-arrays vertically (row wise).
Split array into multiple sub-arrays along the 3rd axis (depth).
Stack a sequence of arrays along a new axis.
Assemble arrays from blocks.
Stack arrays in sequence horizontally (column wise).
Stack arrays in sequence vertically (row wise).
Stack arrays in sequence depth wise (along third dimension).
Stack 1-D arrays as columns into a 2-D array.
When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead.
This function will not preserve masking of MaskedArray inputs.


Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.
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 complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar.
conj is an alias for conjugate:


Returns the discrete, linear convolution of two one-dimensional sequences.
The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions.
If v is longer than a, the arrays are swapped before computation.
First one-dimensional input array.
Second one-dimensional input array.
By default, mode is ‘full’. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen.
Mode ‘same’ returns output of length max(M, N). Boundary effects are still visible.
Mode ‘valid’ returns output of length max(M, N) - min(M, N) + 1. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect.
Discrete, linear convolution of a and v.
See also
Convolve two arrays using the Fast Fourier Transform.
Used to construct the convolution operator.
Polynomial multiplication. Same output as convolve, but also accepts poly1d objects as input.
The discrete convolution operation is defined as
It can be shown that a convolution \(x(t) * y(t)\) in time/space is equivalent to the multiplication \(X(f) Y(f)\) in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function scipy.signal.fftconvolve exploits the FFT to calculate the convolution of large data-sets.
Wikipedia, “Convolution”, https://en.wikipedia.org/wiki/Convolution
Note how the convolution operator flips the second array before “sliding” the two across one another:
Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account:
The two arrays are of the same length, so there is only one position where they completely overlap:


Return an array copy of the given object.
Input data.
Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.)
If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (defaults to False).
New in version 1.19.0.
Array interpretation of a.
See also
Preferred method for creating an array copy
This is equivalent to:
Create an array x, with a reference y and a copy z:
Note that, when we modify x, y changes, but not z:
Note that, np.copy clears previously set WRITEABLE=False flag.
Note that np.copy is a shallow copy and will not copy object elements within arrays. This is mainly important for arrays containing Python objects. The new array will contain the same object which may lead to surprises if that object can be modified (is mutable):
To ensure all elements within an object array are copied, use copy.deepcopy:


Change the sign of x1 to that of x2, element-wise.
If x2 is a scalar, its sign will be copied to all elements of x1.
Values to change the sign of.
The sign of x2 is copied to x1. 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 values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.


Copies values from one array to another, broadcasting as necessary.
Raises a TypeError if the casting rule is violated, and if where is provided, it selects which elements to copy.
New in version 1.7.0.
The array into which values are copied.
The array from which values are copied.
Controls what kind of data casting may occur when copying.
A boolean array which is broadcasted to match the dimensions of dst, and selects elements to copy from src to dst wherever it contains the value True.


Return Pearson product-moment correlation coefficients.
Please refer to the documentation for cov for more detail. The relationship between the correlation coefficient matrix, R, and the covariance matrix, C, is
The values of R are between -1 and 1, inclusive.
A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables. Also see rowvar below.
An additional set of variables and observations. y has the same shape as x.
If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.
Has no effect, do not use.
Deprecated since version 1.10.0.
Has no effect, do not use.
Deprecated since version 1.10.0.
Data-type of the result. By default, the return data-type will have at least numpy.float64 precision.
New in version 1.20.
The correlation coefficient matrix of the variables.
See also
Covariance matrix
Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case.
This function accepts but discards arguments bias and ddof. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy.
In this example we generate two random arrays, xarr and yarr, and compute the row-wise and column-wise Pearson correlation coefficients, R. Since rowvar is true by default, we first find the row-wise Pearson correlation coefficients between the variables of xarr.
If we add another set of variables and observations yarr, we can compute the row-wise Pearson correlation coefficients between the variables in xarr and yarr.
Finally if we use the option rowvar=False, the columns are now being treated as the variables and we will find the column-wise Pearson correlation coefficients between variables in xarr and yarr.


Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Input sequences.
Refer to the convolve docstring. Note that the default is ‘valid’, unlike convolve, which uses ‘full’.
old_behavior was removed in NumPy 1.10. If you need the old behavior, use multiarray.correlate.
Discrete cross-correlation of a and v.
See also
Discrete, linear convolution of two one-dimensional sequences.
Old, no conjugate, version of correlate.
uses FFT which has superior performance on large arrays.
The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is:
which is related to c_{av}[k] by c'_{av}[k] = c_{av}[-k].
numpy.correlate may perform slowly in large arrays (i.e. n = 1e5) because it does not use the FFT to compute the convolution; in that case, scipy.signal.correlate might be preferable.
Using complex sequences:
Note that you get the time reversed, complex conjugated result when the two input sequences change places, i.e., c_{va}[k] = c^{*}_{av}[-k]:


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


Hyperbolic cosine, element-wise.
Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j*x).
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Output array of same shape as x. This is a scalar if x is a scalar.
The hyperbolic cosine describes the shape of a hanging cable:


Counts the number of non-zero values in the array a.
The word “non-zero” is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object’s “truthfulness”. For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True.
The array for which to count non-zeros.
Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of a.
New in version 1.12.0.
If this is set to True, the axes that are counted are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
New in version 1.19.0.
Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.
See also
Return the coordinates of all the non-zero values.


Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, \(X = [x_1, x_2, ... x_N]^T\), then the covariance matrix element \(C_{ij}\) is the covariance of \(x_i\) and \(x_j\). The element \(C_{ii}\) is the variance of \(x_i\).
See the notes for an outline of the algorithm.
A 1-D or 2-D array containing multiple variables and observations. Each row of m represents a variable, and each column a single observation of all those variables. Also see rowvar below.
An additional set of variables and observations. y has the same form as that of m.
If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.
Default normalization (False) is by (N - 1), where N is the number of observations given (unbiased estimate). If bias is True, then normalization is by N. These values can be overridden by using the keyword ddof in numpy versions >= 1.5.
If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified, and ddof=0 will return the simple average. See the notes for the details. The default value is None.
New in version 1.5.
1-D array of integer frequency weights; the number of times each observation vector should be repeated.
New in version 1.10.
1-D array of observation vector weights. These relative weights are typically large for observations considered “important” and smaller for observations considered less “important”. If ddof=0 the array of weights can be used to assign probabilities to observation vectors.
New in version 1.10.
Data-type of the result. By default, the return data-type will have at least numpy.float64 precision.
New in version 1.20.
The covariance matrix of the variables.
See also
Normalized covariance matrix
Assume that the observations are in the columns of the observation array m and let f = fweights and a = aweights for brevity. The steps to compute the weighted covariance are as follows:
Note that when a == 1, the normalization factor v1 / (v1**2 - ddof * v2) goes over to 1 / (np.sum(f) - ddof) as it should.
Consider two variables, \(x_0\) and \(x_1\), which correlate perfectly, but in opposite directions:
Note how \(x_0\) increases while \(x_1\) decreases. The covariance matrix shows this clearly:
Note that element \(C_{0,1}\), which shows the correlation between \(x_0\) and \(x_1\), is negative.
Further, note how x and y are combined:


Return the cross product of two (arrays of) vectors.
The cross product of a and b in \(R^3\) is a vector perpendicular to both a and b. If a and b are arrays of vectors, the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Where the dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned.
Components of the first vector(s).
Components of the second vector(s).
Axis of a that defines the vector(s). By default, the last axis.
Axis of b that defines the vector(s). By default, the last axis.
Axis of c containing the cross product vector(s). Ignored if both input vectors have dimension 2, as the return is scalar. By default, the last axis.
If defined, the axis of a, b and c that defines the vector(s) and cross product(s). Overrides axisa, axisb and axisc.
Vector cross product(s).
When the dimension of the vector(s) in a and/or b does not equal 2 or 3.
See also
Inner product
Outer product.
Construct index arrays.
New in version 1.9.0.
Supports full broadcasting of the inputs.
Vector cross-product.
One vector with dimension 2.
Equivalently:
Both vectors with dimension 2.
Multiple vector cross-products. Note that the direction of the cross product vector is defined by the right-hand rule.
The orientation of c can be changed using the axisc keyword.
Change the vector definition of x and y using axisa and axisb.


Complex number type composed of two single-precision floating-point numbers.
'F'
numpy.singlecomplex
numpy.complex64: Complex number type composed of 2 32-bit-precision floating-point numbers.


Create a numpy array from a ctypes array or POINTER.
The numpy array shares the memory with the ctypes object.
The shape parameter must be given if converting from a ctypes POINTER. The shape parameter is ignored if converting from a ctypes array
Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.
Convert a dtype into a ctypes type.
The dtype to convert
A ctype scalar, union, array, or struct
If the conversion is not possible
This function does not losslessly round-trip in either direction.
np.dtype(as_ctypes_type(dt)) will:
as_ctypes_type(np.dtype(ctype)) will:
It is possible to load a library using
But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. NumPy supplies the load_library function as a convenience.
Changed in version 1.20.0: Allow libname and loader_path to take any path-like object.
Name of the library, which can have ‘lib’ as a prefix, but without an extension.
Where the library can be found.
A ctypes library object
If there is no library with the expected extension, or the library is defective and cannot be loaded.
Array-checking restype/argtypes.
An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, POINTER(c_double), since several restrictions can be specified, which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and flags. If a given array does not satisfy the specified restrictions, a TypeError is raised.
Array data-type.
Number of array dimensions.
Array shape.
Array flags; may be one or more of:
A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags information.
If a given array does not satisfy the specified restrictions.
A ctypes signed integer type of the same size as numpy.intp.
Depending on the platform, it can be an alias for either c_int, c_long or c_longlong.


Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.


Convert a dtype into a ctypes type.
The dtype to convert
A ctype scalar, union, array, or struct
If the conversion is not possible
This function does not losslessly round-trip in either direction.
np.dtype(as_ctypes_type(dt)) will:
as_ctypes_type(np.dtype(ctype)) will:


A ctypes signed integer type of the same size as numpy.intp.
Depending on the platform, it can be an alias for either c_int, c_long or c_longlong.


It is possible to load a library using
But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. NumPy supplies the load_library function as a convenience.
Changed in version 1.20.0: Allow libname and loader_path to take any path-like object.
Name of the library, which can have ‘lib’ as a prefix, but without an extension.
Where the library can be found.
A ctypes library object
If there is no library with the expected extension, or the library is defective and cannot be loaded.


Array-checking restype/argtypes.
An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, POINTER(c_double), since several restrictions can be specified, which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and flags. If a given array does not satisfy the specified restrictions, a TypeError is raised.
Array data-type.
Number of array dimensions.
Array shape.
Array flags; may be one or more of:
A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags information.
If a given array does not satisfy the specified restrictions.


Return the cumulative product of elements along a given axis.
Input array.
Axis along which the cumulative product is computed. By default the input is flattened.
Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.
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 resulting values will be cast if necessary.
A new array holding the result is returned unless out is specified, in which case a reference to out is returned.
See also
Arithmetic is modular when using integer types, and no error is raised on overflow.
The cumulative product for each column (i.e., over the rows) of a:
The cumulative product for each row (i.e. over the columns) of a:


Return the cumulative sum of the elements along a given axis.
Input array.
Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.
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 will be cast if necessary. See Output type determination for more details.
A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.
See also
Sum array elements.
Integration of array values using the composite trapezoidal rule.
Calculate the n-th discrete difference along given axis.
Arithmetic is modular when using integer types, and no error is raised on overflow.
cumsum(a)[-1] may not be equal to sum(a) for floating-point values since sum may use a pairwise summation routine, reducing the roundoff-error. See sum for more information.
cumsum(b)[-1] may not be equal to sum(b)


A generic data source file (file, http, ftp, …).
DataSources can be local files or remote files/URLs. The files may also be compressed or uncompressed. DataSource hides some of the low-level details of downloading the file, allowing you to simply pass in a valid file path (or URL) and obtain a file object.
Path to the directory where the source file gets downloaded to for use. If destpath is None, a temporary directory will be created. The default path is the current directory.
URLs require a scheme string (http://) to be used, without it they will fail:
Temporary directories are deleted when the DataSource is deleted.
abspath(path)
Return absolute path of file in the DataSource directory.
exists(path)
Test if path exists.
open(path[, mode, encoding, newline])
Open and return file-like object.


If created from a 64-bit integer, it represents an offset from 1970-01-01T00:00:00. If created from string, the string can be in ISO 8601 date or datetime format.
See Datetimes and Timedeltas for more information.
'M'


Convert an array of datetimes into an array of strings.
The array of UTC timestamps to format.
One of None, ‘auto’, or a datetime unit.
Timezone information to use when displaying the datetime. If ‘UTC’, end with a Z to indicate UTC time. If ‘local’, convert to the local timezone first, and suffix with a +-#### timezone offset. If a tzinfo object, then do as with ‘local’, but use the specified timezone.
Casting to allow when changing between datetime units.
An array of strings the same shape as arr.
Setting the timezone to UTC shows the same information, but with a Z suffix
Note that we picked datetimes that cross a DST boundary. Passing in a pytz timezone object will print the appropriate offset
Passing in a unit will change the precision
‘casting’ can be used to specify whether precision can be changed


Get information about the step size of a date or time type.
The returned tuple can be passed as the second argument of numpy.datetime64 and numpy.timedelta64.
The dtype object, which must be a datetime64 or timedelta64 type.
The datetime unit on which this dtype is based.
The number of base units in a step.
The result can be used to construct a datetime that uses the same units as a timedelta


Convert angles from degrees to radians.
Angles in degrees.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The corresponding angle in radians. This is a scalar if x is a scalar.
See also
Convert angles from radians to degrees.
Remove large jumps in angle by wrapping.
New in version 1.3.0.
deg2rad(x) is x * pi / 180.


Convert angles from radians to degrees.
Input array in radians.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The corresponding degree values; if out was supplied this is a reference to it. This is a scalar if x is a scalar.
See also
equivalent function
Convert a radian array to degrees


Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj].
Input array.
Indicate indices of sub-arrays to remove along the specified axis.
Changed in version 1.19.0: Boolean indices are now treated as a mask of elements to remove, rather than being cast to the integers 0 and 1.
The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.
A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.
See also
Insert elements into an array.
Append elements at the end of an array.
Often it is preferable to use a boolean mask. For example:
Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further use of mask.


Issues a DeprecationWarning, adds warning to old_name’s docstring, rebinds old_name.__name__ and returns the new function object.
This function may also be used as a decorator.
The function to be deprecated.
The name of the function to be deprecated. Default is None, in which case the name of func is used.
The new name for the function. Default is None, in which case the deprecation message is that old_name is deprecated. If given, the deprecation message is that old_name is deprecated and new_name should be used instead.
Additional explanation of the deprecation. Displayed in the docstring after the warning.
The deprecated function.
Note that olduint returns a value after printing Deprecation Warning:


Deprecates a function and includes the deprecation in its docstring.
This function is used as a decorator. It returns an object that can be used to issue a DeprecationWarning, by passing the to-be decorated function as argument, this adds warning to the to-be decorated function’s docstring and returns the new function object.
Additional explanation of the deprecation. Displayed in the docstring after the warning.
See also
Decorate a function such that it issues a DeprecationWarning


Extract a diagonal or construct a diagonal array.
See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using.
If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.
Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.
The extracted diagonal or constructed diagonal array.
See also
Return specified diagonals.
Create a 2-D array with the flattened input as a diagonal.
Sum along diagonals.
Upper triangle of an array.
Lower triangle of an array.


Return the indices to access the main diagonal of an array.
This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2 dimensions and shape (n, n, …, n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is the set of indices to access a[i, i, ..., i] for i = [0..n-1].
The size, along each dimension, of the arrays for which the returned indices can be used.
The number of dimensions.
See also
New in version 1.4.0.
Create a set of indices to access the diagonal of a (4, 4) array:
Now, we create indices to manipulate a 3-D array:
And use it to set the diagonal of an array of zeros to 1:


Return the indices to access the main diagonal of an n-dimensional array.
See diag_indices for full details.
See also
New in version 1.4.0.


Create a two-dimensional array with the flattened input as a diagonal.
Input data, which is flattened and set as the k-th diagonal of the output.
Diagonal to set; 0, the default, corresponds to the “main” diagonal, a positive (negative) k giving the number of the diagonal above (below) the main.
The 2-D output array.
See also
MATLAB work-alike for 1-D and 2-D arrays.
Return specified diagonals.
Sum along diagonals.


Return specified diagonals.
If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.
In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy of the values in the diagonal.
In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal, but depending on this fact is deprecated. Writing to the resulting array continues to work as it used to, but a FutureWarning is issued.
Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error.
In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array.
If you don’t write to the array returned by this function, then you can just ignore all of the above.
If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a). This will work with both past and future versions of NumPy.
Array from which the diagonals are taken.
Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0).
Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).
Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1).
If a is 2-D, then a 1-D array containing the diagonal and of the same type as a is returned unless a is a matrix, in which case a 1-D array rather than a (2-D) matrix is returned in order to maintain backward compatibility.
If a.ndim > 2, then the dimensions specified by axis1 and axis2 are removed, and a new axis inserted at the end corresponding to the diagonal.
If the dimension of a is less than 2.
See also
MATLAB work-a-like for 1-D and 2-D arrays.
Create diagonal arrays.
Sum along diagonals.
A 3-D example:
The sub-arrays whose main diagonals we just obtained; note that each corresponds to fixing the right-most (column) axis, and that the diagonals are “packed” in rows.
The anti-diagonal can be obtained by reversing the order of elements using either numpy.flipud or numpy.fliplr.
Note that the order in which the diagonal is retrieved varies depending on the flip function.


Calculate the n-th discrete difference along the given axis.
The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively.
Input array
The number of times values are differenced. If zero, the input is returned as-is.
The axis along which the difference is taken, default is the last axis.
Values to prepend or append to a along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match a except along axis.
New in version 1.16.0.
The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. The type of the output is the same as the type of the difference between any two elements of a. This is the same as the type of a in most cases. A notable exception is datetime64, which results in a timedelta64 output array.
See also
Type is preserved for boolean arrays, so the result will contain False when consecutive elements are the same and True when they differ.
For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly:
If this is not desirable, then the array should be cast to a larger integer type first:


Return the indices of the bins to which each value in input array belongs.
right
order of bins
returned index i satisfies
False
increasing
bins[i-1] <= x < bins[i]
True
increasing
bins[i-1] < x <= bins[i]
False
decreasing
bins[i-1] > x >= bins[i]
True
decreasing
bins[i-1] >= x > bins[i]
If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate.
Input array to be binned. Prior to NumPy 1.10.0, this array had to be 1-dimensional, but can now have any shape.
Array of bins. It has to be 1-dimensional and monotonic.
Indicating whether the intervals include the right or the left bin edge. Default behavior is (right==False) indicating that the interval does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins.
Output array of indices, of same shape as x.
If bins is not monotonic.
If the type of the input is complex.
See also
If values in x are such that they fall outside the bin range, attempting to index bins with the indices that digitize returns will result in an IndexError.
New in version 1.10.0.
np.digitize is implemented in terms of np.searchsorted. This means that a binary search is used to bin the values, which scales much better for larger number of bins than the previous linear search. It also removes the requirement for the input array to be 1-dimensional.
For monotonically _increasing_ bins, the following are equivalent:
Note that as the order of the arguments are reversed, the side must be too. The searchsorted call is marginally faster, as it does not do any monotonicity checks. Perhaps more importantly, it supports all dtypes.


Display a message on a device.
Message to display.
Device to write message. If None, defaults to sys.stdout which is very similar to print. device needs to have write() and flush() methods.
Option whether to print a line feed or not. Defaults to True.
If device does not have a write() or flush() method.
Besides sys.stdout, a file-like object can also be used as it has both required methods:


CCompiler_compile(self, sources[, ...])
Compile one or more source files.
CCompiler_customize(self, dist[, need_cxx])
Do any platform-specific customization of a compiler instance.
CCompiler_customize_cmd(self, cmd[, ignore])
Customize compiler using distutils command.
CCompiler_cxx_compiler(self)
Return the C++ compiler.
CCompiler_find_executables(self)
Does nothing here, but is called by the get_version method and can be overridden by subclasses.
CCompiler_get_version(self[, force, ok_status])
Return compiler version, or None if compiler is not available.
CCompiler_object_filenames(self, ...[, ...])
Return the name of the object files for the given source files.
CCompiler_show_customization(self)
Print the compiler customizations to stdout.
CCompiler_spawn(self, cmd[, display, env])
Execute a command in a sub-process.
gen_lib_options(compiler, library_dirs, ...)
new_compiler([plat, compiler, verbose, ...])
replace_method(klass, method_name, func)
simple_version_match([pat, ignore, start])
Simple matching of version numbers, for use in CCompiler and FCompiler.


Provides the CCompilerOpt class, used for handling the CPU/hardware optimization, starting from parsing the command arguments, to managing the relation between the CPU baseline and dispatch-able features, also generating the required C headers and ending with compiling the sources with proper compiler’s flags.
CCompilerOpt doesn’t provide runtime detection for the CPU features, instead only focuses on the compiler side, but it creates abstract C headers that can be used later for the final runtime dispatching process.
new_ccompiler_opt(compiler, dispatch_hpath, ...)
Create a new instance of 'CCompilerOpt' and generate the dispatch header which contains the #definitions and headers of platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features.
CCompilerOpt(ccompiler[, cpu_baseline, ...])
A helper class for CCompiler aims to provide extra build options to effectively control of compiler optimizations that are directly related to CPU features.


A helper class for CCompiler aims to provide extra build options to effectively control of compiler optimizations that are directly related to CPU features.
cache_flush()
Force update the cache.
cc_normalize_flags(flags)
Remove the conflicts that caused due gathering implied features flags.
conf_features_partial()
Return a dictionary of supported CPU features by the platform, and accumulate the rest of undefined options in conf_features, the returned dict has same rules and notes in class attribute conf_features, also its override any options that been set in 'conf_features'.
cpu_baseline_flags()
Returns a list of final CPU baseline compiler flags
cpu_baseline_names()
return a list of final CPU baseline feature names
cpu_dispatch_names()
return a list of final CPU dispatch feature names
dist_compile(sources, flags[, ccompiler])
Wrap CCompiler.compile()
dist_error(*args)
Raise a compiler error
dist_fatal(*args)
Raise a distutils error
dist_info()
Return a tuple containing info about (platform, compiler, extra_args), required by the abstract class '_CCompiler' for discovering the platform environment.
dist_load_module(name, path)
Load a module from file, required by the abstract class '_Cache'.
dist_log(*args[, stderr])
Print a console message
dist_test(source, flags[, macros])
Return True if 'CCompiler.compile()' able to compile a source file with certain flags.
feature_ahead(names)
Return list of features in 'names' after remove any implied features and keep the origins.
feature_c_preprocessor(feature_name[, tabs])
Generate C preprocessor definitions and include headers of a CPU feature.
feature_detect(names)
Return a list of CPU features that required to be detected sorted from the lowest to highest interest.
feature_get_til(names, keyisfalse)
same as feature_implies_c() but stop collecting implied features when feature's option that provided through parameter 'keyisfalse' is False, also sorting the returned features.
feature_implies(names[, keep_origins])
Return a set of CPU features that implied by 'names'
feature_implies_c(names)
same as feature_implies() but combining 'names'
feature_is_exist(name)
Returns True if a certain feature is exist and covered within _Config.conf_features.
feature_names([names, force_flags, macros])
Returns a set of CPU feature names that supported by platform and the C compiler.
feature_sorted(names[, reverse])
Sort a list of CPU features ordered by the lowest interest.
feature_untied(names)
same as 'feature_ahead()' but if both features implied each other and keep the highest interest.
generate_dispatch_header(header_path)
Generate the dispatch header which contains the #definitions and headers for platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features.
is_cached()
Returns True if the class loaded from the cache file
me(cb)
A static method that can be treated as a decorator to dynamically cache certain methods.
parse_targets(source)
Fetch and parse configuration statements that required for defining the targeted CPU features, statements should be declared in the top of source in between C comment and start with a special mark @targets.
try_dispatch(sources[, src_dir, ccompiler])
Compile one or more dispatch-able sources and generates object files, also generates abstract C config headers and macros that used later for the final runtime dispatching process.
cache_hash
cc_test_flags
feature_can_autovec
feature_extra_checks
feature_flags
feature_is_supported
feature_test
report


Extension name.
List of source file locations relative to the top directory of the package.
Extra command line arguments to pass to the compiler.
Extra command line arguments to pass to the fortran77 compiler.
Extra command line arguments to pass to the fortran90 compiler.
has_cxx_sources
has_f2py_sources


Return True if all items in lst are string objects.
Convert a /-separated pathname to one using the OS’s path separator.
Convert a path from Cygwin-native to Windows-native.
Uses the cygpath utility (part of the Base install) to do the actual conversion. Falls back to returning the original path if this fails.
Handles the default /cygdrive mount prefix as well as the /proc/cygdrive portable prefix, custom cygdrive prefixes such as / or /mnt, and absolute paths such as /usr/src/ or /home/username
The path to convert
The converted path
Documentation for cygpath utility: https://cygwin.com/cygwin-ug-net/cygpath.html Documentation for the C function it wraps: https://cygwin.com/cygwin-api/func-cygwin-conv-path.html
Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py.
Use importlib machinery to import a module modname from the file modfile. Depending on the spec.loader, the module may not be registered in sys.modules.
Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively.
Generate config.py file containing system_info information used during building the package.
config[‘py_modules’].append((packagename, ‘__config__’,generate_config_py))
Return frame object from call stack with given level.
Return an info dict for a given C library.
The info dict contains the necessary options to use the C library.
Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.
The dictionary with build information.
If the package is not found.
See also
To get the necessary information for the npymath library from NumPy:
This info dict can then be used as input to a Configuration instance:
Determine language value (c,f77,f90) from sources
Return the MATHLIB line from numpyconfig.h
Get number of parallel build jobs set by the –parallel command line argument of setup.py If the command did not receive a setting the environment variable NPY_NUM_BUILD_JOBS is checked. If that is unset, return the number of processors on the system, with a maximum of 8 (to prevent overloading the system if there a lot of CPUs).
number of parallel jobs that can be run
Return library info for the given package.
Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.
The LibraryInfo instance containing the build information.
If the package is not found.
See also
Apply glob to paths and prepend local_path if needed.
Return True if sources contains C++ files
Return True if sources contains Fortran files
Return true if directory is local directory.
Return true when using mingw32 environment.
Resolve  and ‘.’ from path.
Join two or more pathname components + - convert a /-separated pathname to one using the OS’s path separator. - resolve  and  from path.
Either passing n arguments as in njoin(‘a’,’b’), or a sequence of n names as in njoin([‘a’,’b’]) is handled, or a mixture of such arguments.
Some flags are valid for C but not C++. Prune them.


Convert a /-separated pathname to one using the OS’s path separator.


Convert a path from Cygwin-native to Windows-native.
Uses the cygpath utility (part of the Base install) to do the actual conversion. Falls back to returning the original path if this fails.
Handles the default /cygdrive mount prefix as well as the /proc/cygdrive portable prefix, custom cygdrive prefixes such as / or /mnt, and absolute paths such as /usr/src/ or /home/username
The path to convert
The converted path
Documentation for cygpath utility: https://cygwin.com/cygwin-ug-net/cygpath.html Documentation for the C function it wraps: https://cygwin.com/cygwin-api/func-cygwin-conv-path.html


Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py.


Use importlib machinery to import a module modname from the file modfile. Depending on the spec.loader, the module may not be registered in sys.modules.


Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively.


Generate config.py file containing system_info information used during building the package.
config[‘py_modules’].append((packagename, ‘__config__’,generate_config_py))


Return frame object from call stack with given level.


Return an info dict for a given C library.
The info dict contains the necessary options to use the C library.
Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.
The dictionary with build information.
If the package is not found.
See also
To get the necessary information for the npymath library from NumPy:
This info dict can then be used as input to a Configuration instance:


Determine language value (c,f77,f90) from sources


Return the MATHLIB line from numpyconfig.h


Get number of parallel build jobs set by the –parallel command line argument of setup.py If the command did not receive a setting the environment variable NPY_NUM_BUILD_JOBS is checked. If that is unset, return the number of processors on the system, with a maximum of 8 (to prevent overloading the system if there a lot of CPUs).
number of parallel jobs that can be run


Return library info for the given package.
Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.
The LibraryInfo instance containing the build information.
If the package is not found.
See also


Apply glob to paths and prepend local_path if needed.


Return True if sources contains C++ files


Return True if sources contains Fortran files


Return true if directory is local directory.


Return true when using mingw32 environment.


Join two or more pathname components + - convert a /-separated pathname to one using the OS’s path separator. - resolve  and  from path.
Either passing n arguments as in njoin(‘a’,’b’), or a sequence of n names as in njoin([‘a’,’b’]) is handled, or a mixture of such arguments.


Some flags are valid for C but not C++. Prune them.


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


Return element-wise quotient and remainder simultaneously.
New in version 1.13.0.
np.divmod(x, y) is equivalent to (x // y, x % y), but faster because it avoids redundant work. It is used to implement the Python built-in function divmod on NumPy arrays.
Dividend array.
Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Element-wise quotient resulting from floor division. This is a scalar if both x1 and x2 are scalars.
Element-wise remainder from floor division. This is a scalar if both x1 and x2 are scalars.
See also
Equivalent to Python’s // operator.
Equivalent to Python’s % operator.
Equivalent to divmod(x, 1) for positive x with the return values switched.
The divmod function can be used as a shorthand for np.divmod on ndarrays.


Dot product of two arrays. Specifically,
If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:
First argument.
Second argument.
Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible.
Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.
If the last dimension of a is not the same size as the second-to-last dimension of b.
See also
Complex-conjugating dot product.
Sum products over arbitrary axes.
Einstein summation convention.
‘@’ operator as method with out parameter.
Chained dot product.
Neither argument is complex-conjugated:
For 2-D arrays it is the matrix product:


Double-precision floating-point number type, compatible with Python float and C double.
'd'
numpy.float_
numpy.float64: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.


Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the split documentation. dsplit is equivalent to split with axis=2, the array is always split along the third axis provided the array dimension is greater than or equal to 3.
See also
Split an array into multiple sub-arrays of equal size.


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


Create a data type object.
A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types.
Object to be converted to a data type object.
Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be True only if obj is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flag isalignedstruct.
Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object.
See also
Using array-scalar type:
Structured type, one field name ‘f1’, containing int16:
Structured type, one field named ‘f1’, in itself containing a structured type with one field:
Structured type, two fields: the first field contains an unsigned int, the second an int32:
Using array-protocol type strings:
Using comma-separated field formats. The shape is (2,3):
Using tuples. int is a fixed type, 3 the field’s shape. void is a flexible type, here of size 10:
Subdivide int16 into 2 int8’s, called x and y. 0 and 1 are the offsets in bytes:
Using dictionaries. Two fields named ‘gender’ and ‘age’:
Offsets in bytes, here 0 and 25:
The required alignment (bytes) of this data-type according to the compiler.
Returns dtype for the base element of the subarrays, regardless of their dimension or shape.
A character indicating the byte-order of this data-type object.
A unique character code for each of the 21 different built-in types.
__array_interface__ description of the data-type.
Dictionary of named fields defined for this data type, or None.
Bit-flags describing how this data type is to be interpreted.
Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes.
Boolean indicating whether the dtype is a struct which maintains field alignment.
Integer indicating how this dtype relates to the built-in dtypes.
Boolean indicating whether the byte order of this dtype is native to the platform.
The element size of this data-type object.
A character code (one of ‘biufcmMOSUV’) identifying the general kind of data.
Either None or a readonly dictionary of metadata (mappingproxy).
A bit-width name for this data-type.
Ordered list of field names, or None if there are no fields.
Number of dimensions of the sub-array if this data type describes a sub-array, and 0 otherwise.
A unique number for each of the 21 different built-in types.
Shape tuple of the sub-array if this data type describes a sub-array, and () otherwise.
The array-protocol typestring of this data-type object.
Tuple (item_dtype, shape) if this dtype describes a sub-array, and None otherwise.
newbyteorder([new_order])
Return a new dtype with a different byte order.


Euler’s constant, base of natural logarithms, Napier’s constant.
e = 2.71828182845904523536028747135266249775724709369995...
exp : Exponential function log : Natural logarithm
https://en.wikipedia.org/wiki/E_%28mathematical_constant%29


The differences between consecutive elements of an array.
If necessary, will be flattened before the differences are taken.
Number(s) to append at the end of the returned differences.
Number(s) to prepend at the beginning of the returned differences.
The differences. Loosely, this is ary.flat[1:] - ary.flat[:-1].
See also
When applied to masked arrays, this function drops the mask information if the to_begin and/or to_end parameters are used.
The returned array is always 1D.


Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values.
In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.
See the notes and examples for clarification.
Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator ‘->’ is included as well as subscript labels of the precise output form.
These are the arrays for the operation.
If provided, the calculation is done into this array.
If provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal casting parameter to allow the conversions. Default is None.
Controls the memory layout of the output. ‘C’ means it should be C contiguous. ‘F’ means it should be Fortran contiguous, ‘A’ means it should be ‘F’ if the inputs are all ‘F’, ‘C’ otherwise. ‘K’ means it should be as close to the layout as the inputs as is possible, including arbitrarily permuted axes. Default is ‘K’.
Controls what kind of data casting may occur. Setting this to ‘unsafe’ is not recommended, as it can adversely affect accumulations.
Default is ‘safe’.
Controls if intermediate optimization should occur. No optimization will occur if False and True will default to the ‘greedy’ algorithm. Also accepts an explicit contraction list from the np.einsum_path function. See np.einsum_path for more details. Defaults to False.
The calculation based on the Einstein summation convention.
See also
similar verbose interface is provided by einops package to cover additional operations: transpose, reshape/flatten, repeat/tile, squeeze/unsqueeze and reductions.
opt_einsum optimizes contraction order for einsum-like expressions in backend-agnostic manner.
New in version 1.6.0.
The Einstein summation convention can be used to compute many multi-dimensional, linear algebraic array operations. einsum provides a succinct way of representing these.
A non-exhaustive list of these operations, which can be computed by einsum, is shown below along with examples:
The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Whenever a label is repeated it is summed, so np.einsum('i,i', a, b) is equivalent to np.inner(a,b). If a label appears only once, it is not summed, so np.einsum('i', a) produces a view of a with no changes. A further example np.einsum('ij,jk', a, b) describes traditional matrix multiplication and is equivalent to np.matmul(a,b). Repeated subscript labels in one operand take the diagonal. For example, np.einsum('ii', a) is equivalent to np.trace(a).
In implicit mode, the chosen subscripts are important since the axes of the output are reordered alphabetically. This means that np.einsum('ij', a) doesn’t affect a 2D array, while np.einsum('ji', a) takes its transpose. Additionally, np.einsum('ij,jk', a, b) returns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transpose of the multiplication since subscript ‘h’ precedes subscript ‘i’.
In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier ‘->’ as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like np.sum(a, axis=-1), and np.einsum('ii->i', a) is like np.diag(a). The difference is that einsum does not allow broadcasting by default. Additionally np.einsum('ij,jh->ih', a, b) directly specifies the order of the output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode.
To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b).
When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as np.einsum('ii->i', a) produces a view (changed in version 1.10.0).
einsum also provides an alternative way to provide the subscripts and operands as einsum(op0, sublist0, op1, sublist1, ..., [sublistout]). If the output shape is not provided in this format einsum will be calculated in implicit mode, otherwise it will be performed explicitly. The examples below have corresponding einsum calls with the two parameter methods.
New in version 1.10.0.
Views returned from einsum are now writeable whenever the input array is writeable. For example, np.einsum('ijk...->kji...', a) will now have the same effect as np.swapaxes(a, 0, 2) and np.einsum('ii->i', a) will return a writeable view of the diagonal of a 2D array.
New in version 1.12.0.
Added the optimize argument which will optimize the contraction order of an einsum expression. For a contraction with three or more operands this can greatly increase the computational efficiency at the cost of a larger memory footprint during computation.
Typically a ‘greedy’ algorithm is applied which empirical tests have shown returns the optimal path in the majority of cases. In some cases ‘optimal’ will return the superlative path through a more expensive, exhaustive search. For iterative calculations it may be advisable to calculate the optimal path once and reuse that path by supplying it as an argument. An example is given below.
See numpy.einsum_path for more details.
Trace of a matrix:
Extract the diagonal (requires explicit form):
Sum over an axis (requires explicit form):
For higher dimensional arrays summing a single axis can be done with ellipsis:
Compute a matrix transpose, or reorder any number of axes:
Vector inner products:
Matrix vector multiplication:
Broadcasting and scalar multiplication:
Vector outer product:
Tensor contraction:
Writeable returned arrays (since version 1.10.0):
Example of ellipsis use:
Chained array operations. For more complicated contractions, speed ups might be achieved by repeatedly computing a ‘greedy’ path or pre-computing the ‘optimal’ path and repeatedly applying it, using an einsum_path insertion (since version 1.12.0). Performance improvements can be particularly significant with larger arrays:
Basic einsum: ~1520ms (benchmarked on 3.1GHz Intel i5.)
Sub-optimal einsum (due to repeated path calculation time): ~330ms
Greedy einsum (faster optimal path approximation): ~160ms
Optimal einsum (best usage pattern in some use cases): ~110ms


Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays.
Specifies the subscripts for summation.
These are the arrays for the operation.
Choose the type of path. If a tuple is provided, the second argument is assumed to be the maximum intermediate size created. If only a single argument is provided the largest input or output array size is used as a maximum intermediate size.
Default is ‘greedy’.
A list representation of the einsum path.
A printable representation of the einsum path.
See also
The resulting path indicates which terms of the input contraction should be contracted first, the result of this contraction is then appended to the end of the contraction list. This list can then be iterated over until all intermediate contractions are complete.
We can begin with a chain dot example. In this case, it is optimal to contract the b and c tensors first as represented by the first element of the path (1, 2). The resulting tensor is added to the end of the contraction and the remaining contraction (0, 1) is then completed.
A more complex index transformation example.


Return a new array of given shape and type, without initializing entries.
Shape of the empty array, e.g., (2, 3) or 2.
Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64.
Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
See also
Return an empty array with shape and type of input.
Return a new array setting values to one.
Return a new array setting values to zero.
Return a new array of given shape filled with value.
empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.


Return a new array with the same shape and type as a given array.
The shape and data-type of prototype define these same attributes of the returned array.
Overrides the data type of the result.
New in version 1.6.0.
Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if prototype is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of prototype as closely as possible.
New in version 1.6.0.
If True, then the newly created array will use the sub-class type of prototype, otherwise it will be a base-class array. Defaults to True.
Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.
New in version 1.17.0.
Array of uninitialized (arbitrary) data with the same shape and type as prototype.
See also
Return an array of ones with shape and type of input.
Return an array of zeros with shape and type of input.
Return a new array with shape of input filled with value.
Return a new uninitialized array.
This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be marginally faster than the functions that do set the array values.


Return (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
What is compared are values, not types. So an int (1) and an array of length one can evaluate as True:
The == operator can be used as a shorthand for np.equal on ndarrays.