Undocumented
Variable | array_function_dispatch |
Undocumented |
Variable | False_ |
Undocumented |
Variable | little_endian |
Undocumented |
Variable | newaxis |
Undocumented |
Variable | True_ |
Undocumented |
Variable | ufunc |
Undocumented |
Class | AxisError |
Axis supplied was invalid. |
Class | ComplexWarning |
The warning raised when casting a complex dtype to a real dtype. |
Class | TooHardError |
Undocumented |
Function | _allclose_dispatcher |
Undocumented |
Function | _argwhere_dispatcher |
Undocumented |
Function | _array_equal_dispatcher |
Undocumented |
Function | _array_equiv_dispatcher |
Undocumented |
Function | _convolve_dispatcher |
Undocumented |
Function | _correlate_dispatcher |
Undocumented |
Function | _count_nonzero_dispatcher |
Undocumented |
Function | _cross_dispatcher |
Undocumented |
Function | _flatnonzero_dispatcher |
Undocumented |
Function | _frombuffer |
Undocumented |
Function | _fromfunction_dispatcher |
Undocumented |
Function | _full_dispatcher |
Undocumented |
Function | _full_like_dispatcher |
Undocumented |
Function | _identity_dispatcher |
Undocumented |
Function | _isclose_dispatcher |
Undocumented |
Function | _maketup |
Undocumented |
Function | _moveaxis_dispatcher |
Undocumented |
Function | _ones_dispatcher |
Undocumented |
Function | _ones_like_dispatcher |
Undocumented |
Function | _outer_dispatcher |
Undocumented |
Function | _roll_dispatcher |
Undocumented |
Function | _rollaxis_dispatcher |
Undocumented |
Function | _tensordot_dispatcher |
Undocumented |
Function | _zeros_like_dispatcher |
Undocumented |
Function | allclose |
Returns True if two arrays are element-wise equal within a tolerance. |
Function | argwhere |
Find the indices of array elements that are non-zero, grouped by element. |
Function | array_equal |
True if two arrays have the same shape and elements, False otherwise. |
Function | array_equiv |
Returns True if input arrays are shape consistent and all elements equal. |
Function | base_repr |
Return a string representation of a number in the given base system. |
Function | binary_repr |
Return the binary representation of the input number as a string. |
Function | convolve |
Returns the discrete, linear convolution of two one-dimensional sequences. |
Function | correlate |
Cross-correlation of two 1-dimensional sequences. |
Function | count_nonzero |
Counts the number of non-zero values in the array a. |
Function | cross |
Return the cross product of two (arrays of) vectors. |
Function | extend_all |
Undocumented |
Function | flatnonzero |
Return indices that are non-zero in the flattened version of a. |
Function | fromfunction |
Construct an array by executing a function over each coordinate. |
Function | full |
Return a new array of given shape and type, filled with fill_value . |
Function | full_like |
Return a full array with the same shape and type as a given array. |
Function | identity |
Return the identity array. |
Function | indices |
Return an array representing the indices of a grid. |
Function | isclose |
Returns a boolean array where two arrays are element-wise equal within a tolerance. |
Function | isfortran |
Check if the array is Fortran contiguous but not C contiguous. |
Function | isscalar |
Returns True if the type of element is a scalar type. |
Function | moveaxis |
Move axes of an array to new positions. |
Function | normalize_axis_tuple |
Normalizes an axis argument into a tuple of non-negative integer axes. |
Function | ones |
Return a new array of given shape and type, filled with ones. |
Function | ones_like |
Return an array of ones with the same shape and type as a given array. |
Function | outer |
Compute the outer product of two vectors. |
Function | roll |
Roll array elements along a given axis. |
Function | rollaxis |
Roll the specified axis backwards, until it lies in a given position. |
Function | tensordot |
Compute tensor dot product along specified axes. |
Function | zeros_like |
Return an array of zeros with the same shape and type as a given array. |
Variable | _fromfunction_with_like |
Undocumented |
Variable | _full_with_like |
Undocumented |
Variable | _identity_with_like |
Undocumented |
Variable | _ones_with_like |
Undocumented |
Undocumented
Returns True if two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The
relative difference (rtol
* abs(b
)) and the absolute difference
atol
are added together to compare against the absolute difference
between a
and b
.
NaNs are treated as equal if they are in the same place and if equal_nan=True. Infs are treated as equal if they are in the same place and of the same sign in both arrays.
Whether to compare NaN's as equal. If True, NaN's in a
will be
considered equal to NaN's in b
in the output array.
isclose, all, any, equal
If the following equation is element-wise True, then allclose returns True.
absolute(a
-b
) <= (atol
+rtol
* absolute(b
))
The above equation is not symmetric in a
and b
, so that
allclose(a, b) might be different from allclose(b, a) in
some rare cases.
The comparison of a
and b
uses standard broadcasting, which
means that a
and b
need not have the same shape in order for
allclose(a, b) to evaluate to True. The same is true for
equal
but not array_equal
.
allclose
is not defined for non-numeric data types.
bool
is considered a numeric data-type for this purpose.
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) False >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) True >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) True
Find the indices of array elements that are non-zero, grouped by element.
where, nonzero
np.argwhere(a) is almost the same as np.transpose(np.nonzero(a)), but produces a result of the correct shape for a 0D array.
The output of argwhere is not suitable for indexing arrays. For this purpose use nonzero(a) instead.
>>> x = np.arange(6).reshape(2,3) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.argwhere(x>1) array([[0, 2], [1, 0], [1, 1], [1, 2]])
True if two arrays have the same shape and elements, False otherwise.
Whether to compare NaN's as equal. If the dtype of a1 and a2 is complex, values will be considered equal if either the real or the imaginary component of a given value is nan.
>>> np.array_equal([1, 2], [1, 2]) True >>> np.array_equal(np.array([1, 2]), np.array([1, 2])) True >>> np.array_equal([1, 2], [1, 2, 3]) False >>> np.array_equal([1, 2], [1, 4]) False >>> a = np.array([1, np.nan]) >>> np.array_equal(a, a) False >>> np.array_equal(a, a, equal_nan=True) True
When equal_nan is True, complex values with nan components are considered equal if either the real or the imaginary components are nan.
>>> a = np.array([1 + 1j]) >>> b = a.copy() >>> a.real = np.nan >>> b.imag = np.nan >>> np.array_equal(a, b, equal_nan=True) True
Returns True if input arrays are shape consistent and all elements equal.
Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one.
>>> np.array_equiv([1, 2], [1, 2]) True >>> np.array_equiv([1, 2], [1, 3]) False
Showing the shape equivalence:
>>> np.array_equiv([1, 2], [[1, 2], [1, 2]]) True >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]]) False
>>> np.array_equiv([1, 2], [[1, 2], [1, 3]]) False
Return a string representation of a number in the given base system.
number
to the base
number system. The valid range is 2-36,
the default value is 2.number
in base
system.binary_repr : Faster version of base_repr
for base 2.
>>> np.base_repr(5) '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012'
>>> np.base_repr(10, base=16) 'A' >>> np.base_repr(32, base=16) '20'
Return the binary representation of the input number as a string.
For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two's complement of the number is returned, with respect to that width.
In a two's-complement system negative numbers are represented by the two's complement of the absolute value. This is the most common method of representing signed integers on computers [1]. A N-bit two's-complement system can represent every integer in the range − 2N − 1 to + 2N − 1 − 1.
The length of the returned string if num
is positive, or the length
of the two's complement if num
is negative, provided that width
is
at least a sufficient number of bits for num
to be represented in the
designated form.
If the width
value is insufficient, it will be ignored, and num
will
be returned in binary (num
> 0) or two's complement (num
< 0) form
with its width equal to the minimum number of bits needed to represent
the number in the designated form. This behavior is deprecated and will
later raise an error.
num
or two's complement of num
.bin: Python's built-in binary representation generator of an integer.
binary_repr
is equivalent to using base_repr
with base 2, but about 25x
faster.
[1] | Wikipedia, "Two's complement", https://en.wikipedia.org/wiki/Two's_complement |
>>> np.binary_repr(3) '11' >>> np.binary_repr(-3) '-11' >>> np.binary_repr(3, width=4) '0011'
The two's complement is returned when the input number is negative and width is specified:
>>> np.binary_repr(-3, width=3) '101' >>> np.binary_repr(-3, width=5) '11101'
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.
a
and v
.scipy.linalg.toeplitz : Used to construct the convolution operator. polymul : 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.
[1] | Wikipedia, "Convolution", https://en.wikipedia.org/wiki/Convolution |
Note how the convolution operator flips the second array before "sliding" the two across one another:
>>> np.convolve([1, 2, 3], [0, 1, 0.5]) array([0. , 1. , 2.5, 4. , 1.5])
Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account:
>>> np.convolve([1,2,3],[0,1,0.5], 'same') array([1. , 2.5, 4. ])
The two arrays are of the same length, so there is only one position where they completely overlap:
>>> np.convolve([1,2,3],[0,1,0.5], 'valid') array([2.5])
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
c_{av}[k] = sum_n a[n+k] * conj(v[n])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
a
and v
.convolve : Discrete, linear convolution of two one-dimensional sequences. multiarray.correlate : Old, no conjugate, version of correlate. scipy.signal.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:
c'_{av}[k] = sum_n a[n] conj(v[n+k])
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.
>>> np.correlate([1, 2, 3], [0, 1, 0.5]) array([3.5]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") array([2. , 3.5, 3. ]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") array([0.5, 2. , 3.5, 3. , 0. ])
Using complex sequences:
>>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full') array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
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]:
>>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full') array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
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.
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.
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.
nonzero : Return the coordinates of all the non-zero values.
>>> np.count_nonzero(np.eye(4)) 4 >>> a = np.array([[0, 1, 7, 0], ... [3, 0, 2, 19]]) >>> np.count_nonzero(a) 5 >>> np.count_nonzero(a, axis=0) array([1, 1, 2, 1]) >>> np.count_nonzero(a, axis=1) array([2, 3]) >>> np.count_nonzero(a, axis=1, keepdims=True) array([[2], [3]])
Return the cross product of two (arrays of) vectors.
The cross product of a
and b
in R3 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.
a
that defines the vector(s). By default, the last axis.b
that defines the vector(s). By default, the last axis.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.a
, b
and c
that defines the vector(s)
and cross product(s). Overrides axisa
, axisb
and axisc
.a
and/or b
does not
equal 2 or 3.inner : Inner product outer : Outer product. ix_ : Construct index arrays.
Supports full broadcasting of the inputs.
Vector cross-product.
>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> np.cross(x, y) array([-3, 6, -3])
One vector with dimension 2.
>>> x = [1, 2] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3])
Equivalently:
>>> x = [1, 2, 0] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3])
Both vectors with dimension 2.
>>> x = [1,2] >>> y = [4,5] >>> np.cross(x, y) array(-3)
Multiple vector cross-products. Note that the direction of the cross
product vector is defined by the right-hand rule
.
>>> x = np.array([[1,2,3], [4,5,6]]) >>> y = np.array([[4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[-3, 6, -3], [ 3, -6, 3]])
The orientation of c
can be changed using the axisc
keyword.
>>> np.cross(x, y, axisc=0) array([[-3, 3], [ 6, -6], [-3, 3]])
Change the vector definition of x
and y
using axisa
and axisb
.
>>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]]) >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[ -6, 12, -6], [ 0, 0, 0], [ 6, -12, 6]]) >>> np.cross(x, y, axisa=0, axisb=0) array([[-24, 48, -24], [-30, 60, -30], [-36, 72, -36]])
Return indices that are non-zero in the flattened version of a.
This is equivalent to np.nonzero(np.ravel(a))[0].
a.ravel()
that are non-zero.nonzero : Return the indices of the non-zero elements of the input array. ravel : Return a 1-D array containing the elements of the input array.
>>> x = np.arange(-2, 3) >>> x array([-2, -1, 0, 1, 2]) >>> np.flatnonzero(x) array([0, 1, 3, 4])
Use the indices of the non-zero elements as an index array to extract these elements:
>>> x.ravel()[np.flatnonzero(x)] array([-2, -1, 1, 2])
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).
shape
. Each parameter represents the coordinates of the array
varying along a specific axis. For example, if shape
were (2, 2), then the parameters would be
array([[0, 0], [1, 1]]) and array([[0, 1], [0, 1]])function
.function
.
By default, dtype
is float.${ARRAY_FUNCTION_LIKE}
New in version 1.20.0.
function
is passed back directly.
Therefore the shape of fromfunction
is completely determined by
function
. If function
returns a scalar value, the shape of
fromfunction
would not match the shape
parameter.indices, meshgrid
Keywords other than dtype
are passed to function
.
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) array([[ True, False, False], [False, True, False], [False, False, True]])
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
Return a new array of given shape and type, filled with fill_value
.
${ARRAY_FUNCTION_LIKE}
New in version 1.20.0.
fill_value
with the given shape, dtype, and order.full_like : Return a new array with shape of input filled with value. empty : Return a new uninitialized array. ones : Return a new array setting values to one. zeros : Return a new array setting values to zero.
>>> np.full((2, 2), np.inf) array([[inf, inf], [inf, inf]]) >>> np.full((2, 2), 10) array([[10, 10], [10, 10]])
>>> np.full((2, 2), [1, 2]) array([[1, 2], [1, 2]])
Return a full array with the same shape and type as a given array.
a
define these same attributes of
the returned array.a
is Fortran contiguous,
'C' otherwise. 'K' means match the layout of a
as closely
as possible.a
, otherwise it will be a base-class array. Defaults
to True.Overrides the shape of the result. If order='K' and the number of dimensions is unchanged, will try to keep order, otherwise, order='C' is implied.
fill_value
with the same shape and type as a
.empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. full : Return a new array of given shape filled with value.
>>> x = np.arange(6, dtype=int) >>> np.full_like(x, 1) array([1, 1, 1, 1, 1, 1]) >>> np.full_like(x, 0.1) array([0, 0, 0, 0, 0, 0]) >>> np.full_like(x, 0.1, dtype=np.double) array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.full_like(x, np.nan, dtype=np.double) array([nan, nan, nan, nan, nan, nan])
>>> y = np.arange(6, dtype=np.double) >>> np.full_like(y, 0.1) array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
Return the identity array.
The identity array is a square array with ones on the main diagonal.
n
x n
output.${ARRAY_FUNCTION_LIKE}
New in version 1.20.0.
n
x n
array with its main diagonal set to one,
and all other elements 0.>>> np.identity(3) array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis.
Return a sparse representation of the grid instead of a dense representation. Default is False.
mgrid, ogrid, meshgrid
The output shape in the dense case is obtained by prepending the number
of dimensions in front of the tuple of dimensions, i.e. if dimensions
is a tuple (r0, ..., rN-1) of length N, the output shape is
(N, r0, ..., rN-1).
The subarrays grid[k] contains the N-D array of indices along the k-th axis. Explicitly:
grid[k, i0, i1, ..., iN-1] = ik
>>> grid = np.indices((2, 3)) >>> grid.shape (2, 2, 3) >>> grid[0] # row indices array([[0, 0, 0], [1, 1, 1]]) >>> grid[1] # column indices array([[0, 1, 2], [0, 1, 2]])
The indices can be used as an index into an array.
>>> x = np.arange(20).reshape(5, 4) >>> row, col = np.indices((2, 3)) >>> x[row, col] array([[0, 1, 2], [4, 5, 6]])
Note that it would be more straightforward in the above example to extract the required elements directly with x[:2, :3].
If sparse is set to true, the grid will be returned in a sparse representation.
>>> i, j = np.indices((2, 3), sparse=True) >>> i.shape (2, 1) >>> j.shape (1, 3) >>> i # row indices array([[0], [1]]) >>> j # column indices array([[0, 1, 2]])
Returns a boolean array where two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The
relative difference (rtol
* abs(b
)) and the absolute difference
atol
are added together to compare against the absolute difference
between a
and b
.
Warning
The default atol
is not appropriate for comparing numbers
that are much smaller than one (see Notes).
a
will be
considered equal to NaN's in b
in the output array.a
and b
are equal within the
given tolerance. If both a
and b
are scalars, returns a single
boolean value.allclose math.isclose
For finite values, isclose uses the following equation to test whether two floating point values are equivalent.
absolute(a
-b
) <= (atol
+rtol
* absolute(b
))
Unlike the built-in math.isclose
, the above equation is not symmetric
in a
and b
-- it assumes b
is the reference value -- so that
isclose(a, b)
might be different from isclose(b, a)
. Furthermore,
the default value of atol is not zero, and is used to determine what
small values should be considered close to zero. The default value is
appropriate for expected values of order unity: if the expected values
are significantly smaller than one, it can result in false positives.
atol
should be carefully selected for the use case at hand. A zero value
for atol
will result in False
if either a
or b
is zero.
isclose
is not defined for non-numeric data types.
bool
is considered a numeric data-type for this purpose.
>>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) array([ True, False]) >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) array([ True, True]) >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) array([False, True]) >>> np.isclose([1.0, np.nan], [1.0, np.nan]) array([ True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) array([ True, True]) >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) array([ True, False]) >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) array([False, False]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) array([ True, True]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) array([False, True])
Check if the array is Fortran contiguous but not C contiguous.
This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran contiguous use a.flags.f_contiguous instead.
np.array allows to specify whether the array is written in C-contiguous order (last index varies the fastest), or FORTRAN-contiguous order in memory (first index varies the fastest).
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False
>>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F') >>> b array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(b) True
The transpose of a C-ordered array is a FORTRAN-ordered array.
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False >>> b = a.T >>> b array([[1, 4], [2, 5], [3, 6]]) >>> np.isfortran(b) True
C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
>>> np.isfortran(np.array([1, 2], order='F')) False
Returns True if the type of element
is a scalar type.
element
is a scalar type, False if it is not.ndim : Get the number of dimensions of an array
If you need a stricter way to identify a numerical scalar, use isinstance(x, numbers.Number), as that returns False for most non-numerical elements such as strings.
In most cases np.ndim(x) == 0 should be used instead of this function,
as that will also return true for 0d arrays. This is how numpy overloads
functions in the style of the dx arguments to gradient
and the bins
argument to histogram
. Some key differences:
x | isscalar(x) | np.ndim(x) == 0 |
---|---|---|
PEP 3141 numeric objects (including builtins) | True | True |
builtin string and buffer objects | True | True |
other builtin objects, like
pathlib.Path , Exception ,
the result of re.compile |
False | True |
third-party objects like
matplotlib.figure.Figure |
False | True |
zero-dimensional numpy arrays | False | True |
other numpy arrays | False | False |
list , tuple , and other sequence
objects |
False | False |
>>> np.isscalar(3.1) True >>> np.isscalar(np.array(3.1)) False >>> np.isscalar([3.1]) False >>> np.isscalar(False) True >>> np.isscalar('numpy') True
NumPy supports PEP 3141 numbers:
>>> from fractions import Fraction >>> np.isscalar(Fraction(5, 17)) True >>> from numbers import Number >>> np.isscalar(Number()) True
Move axes of an array to new positions.
Other axes remain in their original order.
transpose : Permute the dimensions of an array. swapaxes : Interchange two axes of an array.
>>> x = np.zeros((3, 4, 5)) >>> np.moveaxis(x, 0, -1).shape (4, 5, 3) >>> np.moveaxis(x, -1, 0).shape (5, 3, 4)
These all achieve the same result:
>>> np.transpose(x).shape (5, 4, 3) >>> np.swapaxes(x, 0, -1).shape (5, 4, 3) >>> np.moveaxis(x, [0, 1], [-1, -2]).shape (5, 4, 3) >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape (5, 4, 3)
Normalizes an axis argument into a tuple of non-negative integer axes.
This handles shorthands such as 1 and converts them to (1,),
as well as performing the handling of negative indices covered by
normalize_axis_index
.
By default, this forbids axes from being specified multiple times.
Used internally by multi-axis-checking logic.
axis
should be normalized
against.0 <= normalized_axis < ndim
normalize_axis_index : normalizing a single scalar axis
Return a new array of given shape and type, filled with ones.
numpy.int8
. Default is
numpy.float64
.${ARRAY_FUNCTION_LIKE}
New in version 1.20.0.
ones_like : Return an array of ones with shape and type of input. empty : Return a new uninitialized array. zeros : Return a new array setting values to zero. full : Return a new array of given shape filled with value.
>>> np.ones(5) array([1., 1., 1., 1., 1.])
>>> np.ones((5,), dtype=int) array([1, 1, 1, 1, 1])
>>> np.ones((2, 1)) array([[1.], [1.]])
>>> s = (2,2) >>> np.ones(s) array([[1., 1.], [1., 1.]])
Return an array of ones with the same shape and type as a given array.
a
define these same attributes of
the returned array.Overrides the data type of the result.
Overrides the memory layout of the result. 'C' means C-order,
'F' means F-order, 'A' means 'F' if a
is Fortran contiguous,
'C' otherwise. 'K' means match the layout of a
as closely
as possible.
a
, otherwise it will be a base-class array. Defaults
to True.Overrides the shape of the result. If order='K' and the number of dimensions is unchanged, will try to keep order, otherwise, order='C' is implied.
a
.empty_like : Return an empty array with shape and type of input. zeros_like : Return an array of zeros with shape and type of input. full_like : Return a new array with shape of input filled with value. ones : Return a new array setting values to one.
>>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.ones_like(x) array([[1, 1, 1], [1, 1, 1]])
>>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.ones_like(y) array([1., 1., 1.])
Compute the outer product of two vectors.
Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [1] is:
[[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]]
A location where the result is stored
inner einsum : einsum('i,j->ij', a.ravel(), b.ravel()) is the equivalent. ufunc.outer : A generalization to dimensions other than 1D and other
operations. np.multiply.outer(a.ravel(), b.ravel()) is the equivalent.
[1] | : G. H. Golub and C. F. Van Loan, Matrix Computations, 3rd ed., Baltimore, MD, Johns Hopkins University Press, 1996, pg. 8. |
Make a (very coarse) grid for computing a Mandelbrot set:
>>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5)) >>> rl array([[-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.]]) >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) >>> im array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) >>> grid = rl + im >>> grid array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j], [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j], [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j], [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j], [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])
An example using a "vector" of letters:
>>> x = np.array(['a', 'b', 'c'], dtype=object) >>> np.outer(x, [1, 2, 3]) array([['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']], dtype=object)
Roll array elements along a given axis.
Elements that roll beyond the last position are re-introduced at the first.
axis
must be a tuple of the same size, and each of the
given axes is shifted by the corresponding number. If an int
while axis
is a tuple of ints, then the same value is used for
all given axes.a
.Supports rolling over multiple dimensions simultaneously.
>>> x = np.arange(10) >>> np.roll(x, 2) array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> np.roll(x, -2) array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
>>> x2 = np.reshape(x, (2, 5)) >>> x2 array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> np.roll(x2, 1) array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]) >>> np.roll(x2, -1) array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]]) >>> np.roll(x2, 1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, -1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, 1, axis=1) array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]) >>> np.roll(x2, -1, axis=1) array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]) >>> np.roll(x2, (1, 1), axis=(1, 0)) array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]) >>> np.roll(x2, (2, 1), axis=(1, 0)) array([[8, 9, 5, 6, 7], [3, 4, 0, 1, 2]])
Roll the specified axis backwards, until it lies in a given position.
This function continues to be supported for backward compatibility, but you
should prefer moveaxis
. The moveaxis
function was added in NumPy
1.11.
When start <= axis, the axis is rolled back until it lies in this position. When start > axis, the axis is rolled until it lies before this position. The default, 0, results in a "complete" roll. The following table describes how negative values of start are interpreted:
start | Normalized start |
---|---|
-(arr.ndim+1) | raise AxisError |
-arr.ndim | 0 |
⋮ | ⋮ |
-1 | arr.ndim-1 |
0 | 0 |
⋮ | ⋮ |
arr.ndim | arr.ndim |
arr.ndim + 1 | raise AxisError |
a
is always returned. For earlier
NumPy versions a view of a
is returned only if the order of the
axes is changed, otherwise the input array is returned.moveaxis : Move array axes to new positions. roll : Roll the elements of an array by a number of positions along a
given axis.
>>> a = np.ones((3,4,5,6)) >>> np.rollaxis(a, 3, 1).shape (3, 6, 4, 5) >>> np.rollaxis(a, 2).shape (5, 3, 4, 6) >>> np.rollaxis(a, 1, 4).shape (3, 5, 6, 4)
Compute tensor dot product along specified axes.
Given two tensors, a
and b
, and an array_like object containing
two array_like objects, (a_axes, b_axes), sum the products of
a
's and b
's elements (components) over the axes specified by
a_axes and b_axes. The third argument can be a single non-negative
integer_like scalar, N; if it is such, then the last N dimensions
of a
and the first N dimensions of b
are summed over.
a
and the first N axes
of b
in order. The sizes of the corresponding axes must match.a
,
second to b
. Both elements array_like must be of the same length.dot, einsum
When axes
is integer_like, the sequence for evaluation will be: first
the -Nth axis in a
and 0th axis in b
, and the -1th axis in a
and
Nth axis in b
last.
When there is more than one axis to sum over - and they are not the last
(first) axes of a
(b
) - the argument axes
should consist of
two sequences of the same length, with the first axis to sum over given
first in both sequences, the second axis second, and so forth.
The shape of the result consists of the non-contracted axes of the first tensor, followed by the non-contracted axes of the second.
A "traditional" example:
>>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape (5, 2) >>> c array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> # A slower but equivalent way of computing the same... >>> d = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): ... for n in range(4): ... d[i,j] += a[k,n,i] * b[n,k,j] >>> c == d array([[ True, True], [ True, True], [ True, True], [ True, True], [ True, True]])
An extended example taking advantage of the overloading of + and *:
>>> a = np.array(range(1, 9)) >>> a.shape = (2, 2, 2) >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object) >>> A.shape = (2, 2) >>> a; A array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) array([['a', 'b'], ['c', 'd']], dtype=object)
>>> np.tensordot(a, A) # third argument default is 2 for double-contraction array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, 1) array([[['acc', 'bdd'], ['aaacccc', 'bbbdddd']], [['aaaaacccccc', 'bbbbbdddddd'], ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
>>> np.tensordot(a, A, 0) # tensor product (result too long to incl.) array([[[[['a', 'b'], ['c', 'd']], ...
>>> np.tensordot(a, A, (0, 1)) array([[['abbbbb', 'cddddd'], ['aabbbbbb', 'ccdddddd']], [['aaabbbbbbb', 'cccddddddd'], ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, (2, 1)) array([[['abb', 'cdd'], ['aaabbbb', 'cccdddd']], [['aaaaabbbbbb', 'cccccdddddd'], ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, ((0, 1), (0, 1))) array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, ((2, 1), (1, 0))) array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
Return an array of zeros with the same shape and type as a given array.
a
define these same attributes of
the returned array.Overrides the data type of the result.
Overrides the memory layout of the result. 'C' means C-order,
'F' means F-order, 'A' means 'F' if a
is Fortran contiguous,
'C' otherwise. 'K' means match the layout of a
as closely
as possible.
a
, otherwise it will be a base-class array. Defaults
to True.Overrides the shape of the result. If order='K' and the number of dimensions is unchanged, will try to keep order, otherwise, order='C' is implied.
a
.empty_like : Return an empty array with shape and type of input. ones_like : Return an array of ones with shape and type of input. full_like : Return a new array with shape of input filled with value. zeros : Return a new array setting values to zero.
>>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.zeros_like(x) array([[0, 0, 0], [0, 0, 0]])
>>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.zeros_like(y) array([0., 0., 0.])