numpy.array   numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)

Create an array.  Parameters

objectarray_like

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned.
dtypedata-type, optional

The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.
copybool, optional

If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).
order{‘K’, ‘A’, ‘C’, ‘F’}, optional

Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds.
order no copy copy=True
‘K’ unchanged F & C order preserved, otherwise most similar order
‘A’ unchanged F order if input is F and not C, otherwise C order
‘C’ C order C order
‘F’ F order F order   When copy=False and a copy is made for other reasons, the result is the same as if copy=True, with some exceptions for ‘A’, see the Notes section. The default order is ‘K’.
subokbool, optional

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
ndminint, optional

Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
likearray_like

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

outndarray

An array object satisfying the specified requirements.      See also  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_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.  full

Return a new array of given shape filled with value.    Notes When order is ‘A’ and object is an array in neither ‘C’ nor ‘F’ order, and a copy is forced by a change in dtype, then the order of the result is not necessarily ‘C’ as expected. This is likely a bug. Examples >>> np.array([1, 2, 3])
array([1, 2, 3])
 Upcasting: >>> np.array([1, 2, 3.0])
array([ 1.,  2.,  3.])
 More than one dimension: >>> np.array([[1, 2], [3, 4]])
array([[1, 2],
       [3, 4]])
 Minimum dimensions 2: >>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])
 Type provided: >>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j,  2.+0.j,  3.+0.j])
 Data-type consisting of more than one element: >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])
 Creating an array from sub-classes: >>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
       [3, 4]])
 >>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
        [3, 4]])


numpy.array2string   numpy.array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix='', style=<no value>, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix='', *, legacy=None)[source]

Return a string representation of an array.  Parameters

andarray

Input array.
max_line_widthint, optional

Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth'].
precisionint or None, optional

Floating point precision. Defaults to numpy.get_printoptions()['precision'].
suppress_smallbool, optional

Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress'].
separatorstr, optional

Inserted between elements.
prefixstr, optional

suffixstr, optional

The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as: prefix + array2string(a) + suffix
 The output is left-padded by the length of the prefix string, and wrapping is forced at the column max_line_width - len(suffix). It should be noted that the content of prefix and suffix strings are not included in the output.
style_NoValue, optional

Has no effect, do not use.  Deprecated since version 1.14.0.
formatterdict of callables, optional

If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:  ‘bool’ ‘int’ ‘timedelta’ : a numpy.timedelta64
 ‘datetime’ : a numpy.datetime64
 ‘float’ ‘longfloat’ : 128-bit floats ‘complexfloat’ ‘longcomplexfloat’ : composed of two 128-bit floats ‘void’ : type numpy.void
 ‘numpystr’ : types numpy.string_ and numpy.unicode_
  Other keys that can be used to set a group of types at once are:  ‘all’ : sets all types ‘int_kind’ : sets ‘int’ ‘float_kind’ : sets ‘float’ and ‘longfloat’ ‘complex_kind’ : sets ‘complexfloat’ and ‘longcomplexfloat’ ‘str_kind’ : sets ‘numpystr’
thresholdint, optional

Total number of array elements which trigger summarization rather than full repr. Defaults to numpy.get_printoptions()['threshold'].
edgeitemsint, optional

Number of array items in summary at beginning and end of each dimension. Defaults to numpy.get_printoptions()['edgeitems'].
signstring, either ‘-’, ‘+’, or ‘ ‘, optional

Controls printing of the sign of floating-point types. If ‘+’, always print the sign of positive values. If ‘ ‘, always prints a space (whitespace character) in the sign position of positive values. If ‘-’, omit the sign character of positive values. Defaults to numpy.get_printoptions()['sign'].
floatmodestr, optional

Controls the interpretation of the precision option for floating-point types. Defaults to numpy.get_printoptions()['floatmode']. Can take the following values:  ‘fixed’: Always print exactly precision fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. ‘unique’: Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the precision option is ignored. ‘maxprec’: Print at most precision fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. ‘maxprec_equal’: Print at most precision fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements.
legacystring or False, optional

If set to the string ‘1.13’ enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to False, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility.  New in version 1.14.0.     Returns

array_strstr

String representation of the array.    Raises
 TypeError

if a callable in formatter does not return a string.      See also
array_str, array_repr, set_printoptions, get_printoptions

  Notes If a formatter is specified for a certain type, the precision keyword is ignored for that type. This is a very flexible function; array_repr and array_str are using array2string internally so keywords with the same name should work identically in all three functions. Examples >>> x = np.array([1e-16,1,2,3])
>>> np.array2string(x, precision=2, separator=',',
...                       suppress_small=True)
'[0.,1.,2.,3.]'
 >>> x  = np.arange(3.)
>>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
'[0.00 1.00 2.00]'
 >>> x  = np.arange(3)
>>> np.array2string(x, formatter={'int':lambda x: hex(x)})
'[0x0 0x1 0x2]'


numpy.array_equal   numpy.array_equal(a1, a2, equal_nan=False)[source]

True if two arrays have the same shape and elements, False otherwise.  Parameters

a1, a2array_like

Input arrays.
equal_nanbool

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.  New in version 1.19.0.     Returns

bbool

Returns True if the arrays are equal.      See also  allclose

Returns True if two arrays are element-wise equal within a tolerance.  array_equiv

Returns True if input arrays are shape consistent and all elements equal.    Examples >>> 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


numpy.array_equiv   numpy.array_equiv(a1, a2)[source]

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

a1, a2array_like

Input arrays.    Returns

outbool

True if equivalent, False otherwise.     Examples >>> 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


numpy.array_repr   numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None)[source]

Return the string representation of an array.  Parameters

arrndarray

Input array.
max_line_widthint, optional

Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth'].
precisionint, optional

Floating point precision. Defaults to numpy.get_printoptions()['precision'].
suppress_smallbool, optional

Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress'].    Returns

stringstr

The string representation of an array.      See also
array_str, array2string, set_printoptions

  Examples >>> np.array_repr(np.array([1,2]))
'array([1, 2])'
>>> np.array_repr(np.ma.array([0.]))
'MaskedArray([0.])'
>>> np.array_repr(np.array([], np.int32))
'array([], dtype=int32)'
 >>> x = np.array([1e-6, 4e-7, 2, 3])
>>> np.array_repr(x, precision=6, suppress_small=True)
'array([0.000001,  0.      ,  2.      ,  3.      ])'


numpy.array_split   numpy.array_split(ary, indices_or_sections, axis=0)[source]

Split an array into multiple sub-arrays. Please refer to the split documentation. The only difference between these functions is that array_split allows indices_or_sections to be an integer that does not equally divide the axis. For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.  See also  split

Split array into multiple sub-arrays of equal size.    Examples >>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([0.,  1.,  2.]), array([3.,  4.,  5.]), array([6.,  7.])]
 >>> x = np.arange(9)
>>> np.array_split(x, 4)
[array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]


numpy.array_str   numpy.array_str(a, max_line_width=None, precision=None, suppress_small=None)[source]

Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type.  Parameters

andarray

Input array.
max_line_widthint, optional

Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth'].
precisionint, optional

Floating point precision. Defaults to numpy.get_printoptions()['precision'].
suppress_smallbool, optional

Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress'].      See also
array2string, array_repr, set_printoptions

  Examples >>> np.array_str(np.arange(3))
'[0 1 2]'


numpy.asanyarray   numpy.asanyarray(a, dtype=None, order=None, *, like=None)

Convert the input to an ndarray, but pass ndarray subclasses through.  Parameters

aarray_like

Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.
dtypedata-type, optional

By default, the data-type is inferred from the input data.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘C’.
likearray_like

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

outndarray or an ndarray subclass

Array interpretation of a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.      See also  asarray

Similar function which always returns ndarrays.  ascontiguousarray

Convert input to a contiguous array.  asfarray

Convert input to a floating point ndarray.  asfortranarray

Convert input to an ndarray with column-major memory order.  asarray_chkfinite

Similar function which checks input for NaNs and Infs.  fromiter

Create an array from an iterator.  fromfunction

Construct an array by executing a function on grid positions.    Examples Convert a list into an array: >>> a = [1, 2]
>>> np.asanyarray(a)
array([1, 2])
 Instances of ndarray subclasses are passed through as-is: >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>> np.asanyarray(a) is a
True


numpy.asarray   numpy.asarray(a, dtype=None, order=None, *, like=None)

Convert the input to an array.  Parameters

aarray_like

Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
dtypedata-type, optional

By default, the data-type is inferred from the input data.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘K’.
likearray_like

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

outndarray

Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.      See also  asanyarray

Similar function which passes through subclasses.  ascontiguousarray

Convert input to a contiguous array.  asfarray

Convert input to a floating point ndarray.  asfortranarray

Convert input to an ndarray with column-major memory order.  asarray_chkfinite

Similar function which checks input for NaNs and Infs.  fromiter

Create an array from an iterator.  fromfunction

Construct an array by executing a function on grid positions.    Examples Convert a list into an array: >>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
 Existing arrays are not copied: >>> a = np.array([1, 2])
>>> np.asarray(a) is a
True
 If dtype is set, array is copied only if dtype does not match: >>> a = np.array([1, 2], dtype=np.float32)
>>> np.asarray(a, dtype=np.float32) is a
True
>>> np.asarray(a, dtype=np.float64) is a
False
 Contrary to asanyarray, ndarray subclasses are not passed through: >>> issubclass(np.recarray, np.ndarray)
True
>>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>> np.asarray(a) is a
False
>>> np.asanyarray(a) is a
True


numpy.asarray_chkfinite   numpy.asarray_chkfinite(a, dtype=None, order=None)[source]

Convert the input to an array, checking for NaNs or Infs.  Parameters

aarray_like

Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs.
dtypedata-type, optional

By default, the data-type is inferred from the input data.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘C’.    Returns

outndarray

Array interpretation of a. No copy is performed if the input is already an ndarray. If a is a subclass of ndarray, a base class ndarray is returned.    Raises
 ValueError

Raises ValueError if a contains NaN (Not a Number) or Inf (Infinity).      See also  asarray

Create and array.  asanyarray

Similar function which passes through subclasses.  ascontiguousarray

Convert input to a contiguous array.  asfarray

Convert input to a floating point ndarray.  asfortranarray

Convert input to an ndarray with column-major memory order.  fromiter

Create an array from an iterator.  fromfunction

Construct an array by executing a function on grid positions.    Examples Convert a list into an array. If all elements are finite asarray_chkfinite is identical to asarray. >>> a = [1, 2]
>>> np.asarray_chkfinite(a, dtype=float)
array([1., 2.])
 Raises ValueError if array_like contains Nans or Infs. >>> a = [1, 2, np.inf]
>>> try:
...     np.asarray_chkfinite(a)
... except ValueError:
...     print('ValueError')
...
ValueError


numpy.ascontiguousarray   numpy.ascontiguousarray(a, dtype=None, *, like=None)

Return a contiguous array (ndim >= 1) in memory (C order).  Parameters

aarray_like

Input array.
dtypestr or dtype object, optional

Data-type of returned array.
likearray_like

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

outndarray

Contiguous array of same shape and content as a, with type dtype if specified.      See also  asfortranarray

Convert input to an ndarray with column-major memory order.  require

Return an ndarray that satisfies requirements.  ndarray.flags

Information about the memory layout of the array.    Examples >>> x = np.arange(6).reshape(2,3)
>>> np.ascontiguousarray(x, dtype=np.float32)
array([[0., 1., 2.],
       [3., 4., 5.]], dtype=float32)
>>> x.flags['C_CONTIGUOUS']
True
 Note: This function returns an array with at least one-dimension (1-d) so it will not preserve 0-d arrays.


numpy.asfarray   numpy.asfarray(a, dtype=<class 'numpy.double'>)[source]

Return an array converted to a float type.  Parameters

aarray_like

The input array.
dtypestr or dtype object, optional

Float type code to coerce input array a. If dtype is one of the ‘int’ dtypes, it is replaced with float64.    Returns

outndarray

The input a as a float ndarray.     Examples >>> np.asfarray([2, 3])
array([2.,  3.])
>>> np.asfarray([2, 3], dtype='float')
array([2.,  3.])
>>> np.asfarray([2, 3], dtype='int8')
array([2.,  3.])


numpy.asfortranarray   numpy.asfortranarray(a, dtype=None, *, like=None)

Return an array (ndim >= 1) laid out in Fortran order in memory.  Parameters

aarray_like

Input array.
dtypestr or dtype object, optional

By default, the data-type is inferred from the input data.
likearray_like

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

outndarray

The input a in Fortran, or column-major, order.      See also  ascontiguousarray

Convert input to a contiguous (C order) array.  asanyarray

Convert input to an ndarray with either row or column-major memory order.  require

Return an ndarray that satisfies requirements.  ndarray.flags

Information about the memory layout of the array.    Examples >>> x = np.arange(6).reshape(2,3)
>>> y = np.asfortranarray(x)
>>> x.flags['F_CONTIGUOUS']
False
>>> y.flags['F_CONTIGUOUS']
True
 Note: This function returns an array with at least one-dimension (1-d) so it will not preserve 0-d arrays.


numpy.asmatrix   numpy.asmatrix(data, dtype=None)[source]

Interpret the input as a matrix. Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False).  Parameters

dataarray_like

Input data.
dtypedata-type

Data-type of the output matrix.    Returns

matmatrix

data interpreted as a matrix.     Examples >>> x = np.array([[1, 2], [3, 4]])
 >>> m = np.asmatrix(x)
 >>> x[0,0] = 5
 >>> m
matrix([[5, 2],
        [3, 4]])


numpy.asscalar   numpy.asscalar(a)[source]

Convert an array of size 1 to its scalar equivalent.  Deprecated since version 1.16: Deprecated, use numpy.ndarray.item() instead.   Parameters

andarray

Input array of size 1.    Returns

outscalar

Scalar representation of a. The output data type is the same type returned by the input’s item method.     Examples >>> np.asscalar(np.array([24]))
24


numpy.atleast_1d   numpy.atleast_1d(*arys)[source]

Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.  Parameters

arys1, arys2, …array_like

One or more input arrays.    Returns

retndarray

An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.      See also
atleast_2d, atleast_3d

  Examples >>> np.atleast_1d(1.0)
array([1.])
 >>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])
>>> np.atleast_1d(x) is x
True
 >>> np.atleast_1d(1, [3, 4])
[array([1]), array([3, 4])]


numpy.atleast_2d   numpy.atleast_2d(*arys)[source]

View inputs as arrays with at least two dimensions.  Parameters

arys1, arys2, …array_like

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.    Returns

res, res2, …ndarray

An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.      See also
atleast_1d, atleast_3d

  Examples >>> np.atleast_2d(3.0)
array([[3.]])
 >>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[0., 1., 2.]])
>>> np.atleast_2d(x).base is x
True
 >>> np.atleast_2d(1, [1, 2], [[1, 2]])
[array([[1]]), array([[1, 2]]), array([[1, 2]])]


numpy.atleast_3d   numpy.atleast_3d(*arys)[source]

View inputs as arrays with at least three dimensions.  Parameters

arys1, arys2, …array_like

One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.    Returns

res1, res2, …ndarray

An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).      See also
atleast_1d, atleast_2d

  Examples >>> np.atleast_3d(3.0)
array([[[3.]]])
 >>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
 >>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x.base  # x is a reshape, so not base itself
True
 >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
...     print(arr, arr.shape)
...
[[[1]
  [2]]] (1, 2, 1)
[[[1]
  [2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2)


numpy.average   numpy.average(a, axis=None, weights=None, returned=False)[source]

Compute the weighted average along the specified axis.  Parameters

aarray_like

Array containing data to be averaged. If a is not an array, a conversion is attempted.
axisNone or int or tuple of ints, optional

Axis or axes along which to average a. The default, axis=None, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis.  New in version 1.7.0.  If axis is a tuple of ints, averaging is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
weightsarray_like, optional

An array of weights associated with the values in a. Each value in a contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as a. If weights=None, then all data in a are assumed to have a weight equal to one. The 1-D calculation is: avg = sum(a * weights) / sum(weights)
 The only constraint on weights is that sum(weights) must not be 0.
returnedbool, optional

Default is False. If True, the tuple (average, sum_of_weights) is returned, otherwise only the average is returned. If weights=None, sum_of_weights is equivalent to the number of elements over which the average is taken.    Returns

retval, [sum_of_weights]array_type or double

Return the average along the specified axis. When returned is True, return a tuple with the average as the first element and the sum of the weights as the second element. sum_of_weights is of the same type as retval. The result dtype follows a genereal pattern. If weights is None, the result dtype will be that of a , or float64 if a is integral. Otherwise, if weights is not None and a is non- integral, the result type will be the type of lowest precision capable of representing values of both a and weights. If a happens to be integral, the previous rules still applies but the result dtype will at least be float64.    Raises
 ZeroDivisionError

When all weights along axis are zero. See numpy.ma.average for a version robust to this type of error.  TypeError

When the length of 1D weights is not the same as the shape of a along axis.      See also  mean
ma.average

average for masked arrays – useful if your data contains “missing” values  numpy.result_type

Returns the type that results from applying the numpy type promotion rules to the arguments.    Examples >>> data = np.arange(1, 5)
>>> data
array([1, 2, 3, 4])
>>> np.average(data)
2.5
>>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1))
4.0
 >>> data = np.arange(6).reshape((3,2))
>>> data
array([[0, 1],
       [2, 3],
       [4, 5]])
>>> np.average(data, axis=1, weights=[1./4, 3./4])
array([0.75, 2.75, 4.75])
>>> np.average(data, weights=[1./4, 3./4])
Traceback (most recent call last):
    ...
TypeError: Axis must be specified when shapes of a and weights differ.
 >>> a = np.ones(5, dtype=np.float128)
>>> w = np.ones(5, dtype=np.complex64)
>>> avg = np.average(a, weights=w)
>>> print(avg.dtype)
complex256


numpy.AxisError   exception numpy.AxisError(axis, ndim=None, msg_prefix=None)[source]

Axis supplied was invalid. This is raised whenever an axis parameter is specified that is larger than the number of array dimensions. For compatibility with code written against older numpy versions, which raised a mixture of ValueError and IndexError for this situation, this exception subclasses both to ensure that except ValueError and except IndexError statements continue to catch AxisError.  New in version 1.13.   Parameters

axisint or str

The out of bounds axis or a custom exception message. If an axis is provided, then ndim should be specified as well.
ndimint, optional

The number of array dimensions.
msg_prefixstr, optional

A prefix for the exception message.     Examples >>> array_1d = np.arange(10)
>>> np.cumsum(array_1d, axis=1)
Traceback (most recent call last):
  ...
numpy.AxisError: axis 1 is out of bounds for array of dimension 1
 Negative axes are preserved: >>> np.cumsum(array_1d, axis=-2)
Traceback (most recent call last):
  ...
numpy.AxisError: axis -2 is out of bounds for array of dimension 1
 The class constructor generally takes the axis and arrays’ dimensionality as arguments: >>> print(np.AxisError(2, 1, msg_prefix='error'))
error: axis 2 is out of bounds for array of dimension 1
 Alternatively, a custom exception message can be passed: >>> print(np.AxisError('Custom error message'))
Custom error message
  Attributes

axisint, optional

The out of bounds axis or None if a custom exception message was provided. This should be the axis as passed by the user, before any normalization to resolve negative indices.  New in version 1.22.
ndimint, optional

The number of array dimensions or None if a custom exception message was provided.  New in version 1.22.


numpy.bartlett   numpy.bartlett(M)[source]

Return the Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain.  Parameters

Mint

Number of points in the output window. If zero or less, an empty array is returned.    Returns

outarray

The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero.      See also
blackman, hamming, hanning, kaiser

  Notes The Bartlett window is defined as  \[w(n) = \frac{2}{M-1} \left( \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right| \right)\] Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means”removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich. References  1
M.S. Bartlett, “Periodogram Analysis and Continuous Spectra”, Biometrika 37, 1-16, 1950.  2
E.R. Kanasewich, “Time Sequence Analysis in Geophysics”, The University of Alberta Press, 1975, pp. 109-110.  3
A.V. Oppenheim and R.W. Schafer, “Discrete-Time Signal Processing”, Prentice-Hall, 1999, pp. 468-471.  4
Wikipedia, “Window function”, https://en.wikipedia.org/wiki/Window_function  5
W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, “Numerical Recipes”, Cambridge University Press, 1986, page 429.   Examples >>> import matplotlib.pyplot as plt
>>> np.bartlett(12)
array([ 0.        ,  0.18181818,  0.36363636,  0.54545455,  0.72727273, # may vary
        0.90909091,  0.90909091,  0.72727273,  0.54545455,  0.36363636,
        0.18181818,  0.        ])
 Plot the window and its frequency response (requires SciPy and matplotlib): >>> from numpy.fft import fft, fftshift
>>> window = np.bartlett(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Bartlett window")
Text(0.5, 1.0, 'Bartlett window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
    >>> plt.figure()
<Figure size 640x480 with 0 Axes>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> with np.errstate(divide='ignore', invalid='ignore'):
...     response = 20 * np.log10(mag)
...
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Bartlett window")
Text(0.5, 1.0, 'Frequency response of Bartlett window')
>>> plt.ylabel("Magnitude [dB]")
Text(0, 0.5, 'Magnitude [dB]')
>>> plt.xlabel("Normalized frequency [cycles per sample]")
Text(0.5, 0, 'Normalized frequency [cycles per sample]')
>>> _ = plt.axis('tight')
>>> plt.show()


numpy.base_repr   numpy.base_repr(number, base=2, padding=0)[source]

Return a string representation of a number in the given base system.  Parameters

numberint

The value to convert. Positive and negative values are handled.
baseint, optional

Convert number to the base number system. The valid range is 2-36, the default value is 2.
paddingint, optional

Number of zeros padded on the left. Default is 0 (no padding).    Returns

outstr

String representation of number in base system.      See also  binary_repr

Faster version of base_repr for base 2.    Examples >>> 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'


numpy.binary_repr   numpy.binary_repr(num, width=None)[source]

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 \(-2^{N-1}\) to \(+2^{N-1}-1\).  Parameters

numint

Only an integer decimal number can be used.
widthint, optional

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.  Deprecated since version 1.12.0.     Returns

binstr

Binary representation of num or two’s complement of num.      See also  base_repr

Return a string representation of a number in the given base system.  bin

Python’s built-in binary representation generator of an integer.    Notes binary_repr is equivalent to using base_repr with base 2, but about 25x faster. References  1
Wikipedia, “Two’s complement”, https://en.wikipedia.org/wiki/Two’s_complement   Examples >>> 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'


numpy.bincount   numpy.bincount(x, /, weights=None, minlength=0)

Count number of occurrences of each value in array of non-negative ints. The number of bins (of size 1) is one larger than the largest value in x. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of x). Each bin gives the number of occurrences of its index value in x. If weights is specified the input array is weighted by it, i.e. if a value n is found at position i, out[n] += weight[i] instead of out[n] += 1.  Parameters

xarray_like, 1 dimension, nonnegative ints

Input array.
weightsarray_like, optional

Weights, array of the same shape as x.
minlengthint, optional

A minimum number of bins for the output array.  New in version 1.6.0.     Returns

outndarray of ints

The result of binning the input array. The length of out is equal to np.amax(x)+1.    Raises
 ValueError

If the input is not 1-dimensional, or contains elements with negative values, or if minlength is negative.  TypeError

If the type of the input is float or complex.      See also
histogram, digitize, unique

  Examples >>> np.bincount(np.arange(5))
array([1, 1, 1, 1, 1])
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])
 >>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
>>> np.bincount(x).size == np.amax(x)+1
True
 The input array needs to be of integer dtype, otherwise a TypeError is raised: >>> np.bincount(np.arange(5, dtype=float))
Traceback (most recent call last):
  ...
TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
according to the rule 'safe'
 A possible use of bincount is to perform sums over variable-size chunks of an array, using the weights keyword. >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
>>> x = np.array([0, 1, 1, 2, 2, 2])
>>> np.bincount(x,  weights=w)
array([ 0.3,  0.7,  1.1])


numpy.bitwise_and   numpy.bitwise_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'bitwise_and'>

Compute the bit-wise AND of two arrays element-wise. Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator &.  Parameters

x1, x2array_like

Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional

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.
wherearray_like, optional

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.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

outndarray or scalar

Result. This is a scalar if both x1 and x2 are scalars.      See also  logical_and
bitwise_or
bitwise_xor
binary_repr

Return the binary representation of the input number as a string.    Examples The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise AND of 13 and 17 is therefore 000000001, or 1: >>> np.bitwise_and(13, 17)
1
 >>> np.bitwise_and(14, 13)
12
>>> np.binary_repr(12)
'1100'
>>> np.bitwise_and([14,3], 13)
array([12,  1])
 >>> np.bitwise_and([11,7], [4,25])
array([0, 1])
>>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16]))
array([ 2,  4, 16])
>>> np.bitwise_and([True, True], [False, True])
array([False,  True])
 The & operator can be used as a shorthand for np.bitwise_and on ndarrays. >>> x1 = np.array([2, 5, 255])
>>> x2 = np.array([3, 14, 16])
>>> x1 & x2
array([ 2,  4, 16])


numpy.bitwise_or   numpy.bitwise_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'bitwise_or'>

Compute the bit-wise OR of two arrays element-wise. Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator |.  Parameters

x1, x2array_like

Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional

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.
wherearray_like, optional

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.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

outndarray or scalar

Result. This is a scalar if both x1 and x2 are scalars.      See also  logical_or
bitwise_and
bitwise_xor
binary_repr

Return the binary representation of the input number as a string.    Examples The number 13 has the binary representation 00001101. Likewise, 16 is represented by 00010000. The bit-wise OR of 13 and 16 is then 000111011, or 29: >>> np.bitwise_or(13, 16)
29
>>> np.binary_repr(29)
'11101'
 >>> np.bitwise_or(32, 2)
34
>>> np.bitwise_or([33, 4], 1)
array([33,  5])
>>> np.bitwise_or([33, 4], [1, 2])
array([33,  6])
 >>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4]))
array([  6,   5, 255])
>>> np.array([2, 5, 255]) | np.array([4, 4, 4])
array([  6,   5, 255])
>>> np.bitwise_or(np.array([2, 5, 255, 2147483647], dtype=np.int32),
...               np.array([4, 4, 4, 2147483647], dtype=np.int32))
array([         6,          5,        255, 2147483647])
>>> np.bitwise_or([True, True], [False, True])
array([ True,  True])
 The | operator can be used as a shorthand for np.bitwise_or on ndarrays. >>> x1 = np.array([2, 5, 255])
>>> x2 = np.array([4, 4, 4])
>>> x1 | x2
array([  6,   5, 255])


numpy.bitwise_xor   numpy.bitwise_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'bitwise_xor'>

Compute the bit-wise XOR of two arrays element-wise. Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ^.  Parameters

x1, x2array_like

Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional

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.
wherearray_like, optional

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.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

outndarray or scalar

Result. This is a scalar if both x1 and x2 are scalars.      See also  logical_xor
bitwise_and
bitwise_or
binary_repr

Return the binary representation of the input number as a string.    Examples The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise XOR of 13 and 17 is therefore 00011100, or 28: >>> np.bitwise_xor(13, 17)
28
>>> np.binary_repr(28)
'11100'
 >>> np.bitwise_xor(31, 5)
26
>>> np.bitwise_xor([31,3], 5)
array([26,  6])
 >>> np.bitwise_xor([31,3], [5,6])
array([26,  5])
>>> np.bitwise_xor([True, True], [False, True])
array([ True, False])
 The ^ operator can be used as a shorthand for np.bitwise_xor on ndarrays. >>> x1 = np.array([True, True])
>>> x2 = np.array([False, True])
>>> x1 ^ x2
array([ True, False])


numpy.blackman   numpy.blackman(M)[source]

Return the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.  Parameters

Mint

Number of points in the output window. If zero or less, an empty array is returned.    Returns

outndarray

The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).      See also
bartlett, hamming, hanning, kaiser

  Notes The Blackman window is defined as  \[w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)\] Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means “removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a “near optimal” tapering function, almost as good (by some measures) as the kaiser window. References Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. Examples >>> import matplotlib.pyplot as plt
>>> np.blackman(12)
array([-1.38777878e-17,   3.26064346e-02,   1.59903635e-01, # may vary
        4.14397981e-01,   7.36045180e-01,   9.67046769e-01,
        9.67046769e-01,   7.36045180e-01,   4.14397981e-01,
        1.59903635e-01,   3.26064346e-02,  -1.38777878e-17])
 Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift
>>> window = np.blackman(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Blackman window")
Text(0.5, 1.0, 'Blackman window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
    >>> plt.figure()
<Figure size 640x480 with 0 Axes>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> with np.errstate(divide='ignore', invalid='ignore'):
...     response = 20 * np.log10(mag)
...
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Blackman window")
Text(0.5, 1.0, 'Frequency response of Blackman window')
>>> plt.ylabel("Magnitude [dB]")
Text(0, 0.5, 'Magnitude [dB]')
>>> plt.xlabel("Normalized frequency [cycles per sample]")
Text(0.5, 0, 'Normalized frequency [cycles per sample]')
>>> _ = plt.axis('tight')
>>> plt.show()


numpy.block   numpy.block(arrays)[source]

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

arraysnested list of array_like or scalars (but not tuples)

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

block_arrayndarray

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    Raises
 ValueError

 If list depths are mismatched - for instance, [[a, b], c] is illegal, and should be spelt [[a, b], [c]]
 If lists are empty - for instance, [[a, b], []]
       See also  concatenate

Join a sequence of arrays along an existing axis.  stack

Join a sequence of arrays along a new axis.  vstack

Stack arrays in sequence vertically (row wise).  hstack

Stack arrays in sequence horizontally (column wise).  dstack

Stack arrays in sequence depth wise (along third axis).  column_stack

Stack 1-D arrays as columns into a 2-D array.  vsplit

Split an array into multiple sub-arrays vertically (row-wise).    Notes 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: AAAbb
AAAbb
cccDD
 But is also allowed to produce, for some a, b, c, d: AAAbb
AAAbb
cDDDD
 Since concatenation happens along the last axis first, block is _not_ capable of producing the following directly: AAAbb
cccbb
cccDD
 Matlab’s “square bracket stacking”, [A, B, ...; p, q, ...], is equivalent to np.block([[A, B, ...], [p, q, ...]]). Examples The most common use of this function is to build a block matrix >>> A = np.eye(2) * 2
>>> B = np.eye(3) * 3
>>> np.block([
...     [A,               np.zeros((2, 3))],
...     [np.ones((3, 2)), B               ]
... ])
array([[2., 0., 0., 0., 0.],
       [0., 2., 0., 0., 0.],
       [1., 1., 3., 0., 0.],
       [1., 1., 0., 3., 0.],
       [1., 1., 0., 0., 3.]])
 With a list of depth 1, block can be used as hstack >>> np.block([1, 2, 3])              # hstack([1, 2, 3])
array([1, 2, 3])
 >>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.block([a, b, 10])             # hstack([a, b, 10])
array([ 1,  2,  3,  4,  5,  6, 10])
 >>> A = np.ones((2, 2), int)
>>> B = 2 * A
>>> np.block([A, B])                 # hstack([A, B])
array([[1, 1, 2, 2],
       [1, 1, 2, 2]])
 With a list of depth 2, block can be used in place of vstack: >>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.block([[a], [b]])             # vstack([a, b])
array([[1, 2, 3],
       [4, 5, 6]])
 >>> A = np.ones((2, 2), int)
>>> B = 2 * A
>>> np.block([[A], [B]])             # vstack([A, B])
array([[1, 1],
       [1, 1],
       [2, 2],
       [2, 2]])
 It can also be used in places of atleast_1d and atleast_2d >>> a = np.array(0)
>>> b = np.array([1])
>>> np.block([a])                    # atleast_1d(a)
array([0])
>>> np.block([b])                    # atleast_1d(b)
array([1])
 >>> np.block([[a]])                  # atleast_2d(a)
array([[0]])
>>> np.block([[b]])                  # atleast_2d(b)
array([[1]])


numpy.bmat   numpy.bmat(obj, ldict=None, gdict=None)[source]

Build a matrix object from a string, nested sequence, or array.  Parameters

objstr or array_like

Input data. If a string, variables in the current scope may be referenced by name.
ldictdict, optional

A dictionary that replaces local operands in current frame. Ignored if obj is not a string or gdict is None.
gdictdict, optional

A dictionary that replaces global operands in current frame. Ignored if obj is not a string.    Returns

outmatrix

Returns a matrix object, which is a specialized 2-D array.      See also  block

A generalization of this function for N-d arrays, that returns normal ndarrays.    Examples >>> A = np.mat('1 1; 1 1')
>>> B = np.mat('2 2; 2 2')
>>> C = np.mat('3 4; 5 6')
>>> D = np.mat('7 8; 9 0')
 All the following expressions construct the same block matrix: >>> np.bmat([[A, B], [C, D]])
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])
>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])
>>> np.bmat('A,B; C,D')
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])


numpy.broadcast   class numpy.broadcast[source]

Produce an object that mimics broadcasting.  Parameters

in1, in2, …array_like

Input parameters.    Returns

bbroadcast object

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  broadcast_arrays
broadcast_to
broadcast_shapes
  Examples Manually adding two vectors, using broadcasting: >>> x = np.array([[1], [2], [3]])
>>> y = np.array([4, 5, 6])
>>> b = np.broadcast(x, y)
 >>> out = np.empty(b.shape)
>>> out.flat = [u+v for (u,v) in b]
>>> out
array([[5.,  6.,  7.],
       [6.,  7.,  8.],
       [7.,  8.,  9.]])
 Compare against built-in broadcasting: >>> x + y
array([[5, 6, 7],
       [6, 7, 8],
       [7, 8, 9]])
  Attributes
 index

current index in broadcasted result  iters

tuple of iterators along self’s “components.”  nd

Number of dimensions of broadcasted result.  ndim

Number of dimensions of broadcasted result.  numiter

Number of iterators possessed by the broadcasted result.  shape

Shape of broadcasted result.  size

Total size of broadcasted result.     Methods
reset() Reset the broadcasted result's iterator(s).


numpy.broadcast_arrays   numpy.broadcast_arrays(*args, subok=False)[source]

Broadcast any number of arrays against each other.  Parameters

`*args`array_likes

The arrays to broadcast.
subokbool, optional

If True, then sub-classes will be passed-through, otherwise the returned arrays will be forced to be a base-class array (default).    Returns

broadcastedlist of arrays

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  broadcast
broadcast_to
broadcast_shapes
  Examples >>> x = np.array([[1,2,3]])
>>> y = np.array([[4],[5]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
       [1, 2, 3]]), array([[4, 4, 4],
       [5, 5, 5]])]
 Here is a useful idiom for getting contiguous copies instead of non-contiguous views. >>> [np.array(a) for a in np.broadcast_arrays(x, y)]
[array([[1, 2, 3],
       [1, 2, 3]]), array([[4, 4, 4],
       [5, 5, 5]])]


numpy.broadcast_shapes   numpy.broadcast_shapes(*args)[source]

Broadcast the input shapes into a single shape. Learn more about broadcasting here.  New in version 1.20.0.   Parameters

`*args`tuples of ints, or ints

The shapes to be broadcast against each other.    Returns
 tuple

Broadcasted shape.    Raises
 ValueError

If the shapes are not compatible and cannot be broadcast according to NumPy’s broadcasting rules.      See also  broadcast
broadcast_arrays
broadcast_to
  Examples >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2))
(3, 2)
 >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7))
(5, 6, 7)


numpy.broadcast_to   numpy.broadcast_to(array, shape, subok=False)[source]

Broadcast an array to a new shape.  Parameters

arrayarray_like

The array to broadcast.
shapetuple or int

The shape of the desired array. A single integer i is interpreted as (i,).
subokbool, optional

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).    Returns

broadcastarray

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.    Raises
 ValueError

If the array is not compatible with the new shape according to NumPy’s broadcasting rules.      See also  broadcast
broadcast_arrays
broadcast_shapes
  Notes  New in version 1.10.0.  Examples >>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])


numpy.busday_count   numpy.busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None)

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

begindatesarray_like of datetime64[D]

The array of the first dates for counting.
enddatesarray_like of datetime64[D]

The array of the end dates for counting, which are excluded from the count themselves.
weekmaskstr or array_like of bool, optional

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
holidaysarray_like of datetime64[D], optional

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.
busdaycalbusdaycalendar, optional

A busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided.
outarray of int, optional

If provided, this array is filled with the result.    Returns

outarray of int

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  busdaycalendar

An object that specifies a custom set of valid days.  is_busday

Returns a boolean array indicating valid days.  busday_offset

Applies an offset counted in valid days.    Examples >>> # Number of weekdays in January 2011
... np.busday_count('2011-01', '2011-02')
21
>>> # Number of weekdays in 2011
>>> np.busday_count('2011', '2012')
260
>>> # Number of Saturdays in 2011
... np.busday_count('2011', '2012', weekmask='Sat')
53


numpy.busday_offset   numpy.busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None)

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

datesarray_like of datetime64[D]

The array of dates to process.
offsetsarray_like of int

The array of offsets, which is broadcast with dates.
roll{‘raise’, ‘nat’, ‘forward’, ‘following’, ‘backward’, ‘preceding’, ‘modifiedfollowing’, ‘modifiedpreceding’}, optional

How to treat dates that do not fall on a valid day. The default is ‘raise’.  ‘raise’ means to raise an exception for an invalid day. ‘nat’ means to return a NaT (not-a-time) for an invalid day. ‘forward’ and ‘following’ mean to take the first valid day later in time. ‘backward’ and ‘preceding’ mean to take the first valid day earlier in time. ‘modifiedfollowing’ means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time. ‘modifiedpreceding’ means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time.
weekmaskstr or array_like of bool, optional

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
holidaysarray_like of datetime64[D], optional

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.
busdaycalbusdaycalendar, optional

A busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided.
outarray of datetime64[D], optional

If provided, this array is filled with the result.    Returns

outarray of datetime64[D]

An array with a shape from broadcasting dates and offsets together, containing the dates with offsets applied.      See also  busdaycalendar

An object that specifies a custom set of valid days.  is_busday

Returns a boolean array indicating valid days.  busday_count

Counts how many valid days are in a half-open date range.    Examples >>> # First business day in October 2011 (not accounting for holidays)
... np.busday_offset('2011-10', 0, roll='forward')
numpy.datetime64('2011-10-03')
>>> # Last business day in February 2012 (not accounting for holidays)
... np.busday_offset('2012-03', -1, roll='forward')
numpy.datetime64('2012-02-29')
>>> # Third Wednesday in January 2011
... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
numpy.datetime64('2011-01-19')
>>> # 2012 Mother's Day in Canada and the U.S.
... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
numpy.datetime64('2012-05-13')
 >>> # First business day on or after a date
... np.busday_offset('2011-03-20', 0, roll='forward')
numpy.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 0, roll='forward')
numpy.datetime64('2011-03-22')
>>> # First business day after a date
... np.busday_offset('2011-03-20', 1, roll='backward')
numpy.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 1, roll='backward')
numpy.datetime64('2011-03-23')


numpy.busdaycalendar   class numpy.busdaycalendar(weekmask='1111100', holidays=None)[source]

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

weekmaskstr or array_like of bool, optional

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
holidaysarray_like of datetime64[D], optional

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

outbusdaycalendar

A business day calendar object containing the specified weekmask and holidays values.      See also  is_busday

Returns a boolean array indicating valid days.  busday_offset

Applies an offset counted in valid days.  busday_count

Counts how many valid days are in a half-open date range.    Examples >>> # Some important days in July
... bdd = np.busdaycalendar(
...             holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
>>> # Default is Monday to Friday weekdays
... bdd.weekmask
array([ True,  True,  True,  True,  True, False, False])
>>> # Any holidays already on the weekend are removed
... bdd.holidays
array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')
  Attributes
 Note: once a busdaycalendar object is created, you cannot modify the
weekmask or holidays. The attributes return copies of internal data.

weekmask(copy) seven-element array of bool

A copy of the seven-element boolean mask indicating valid days.
holidays(copy) sorted array of datetime64[D]

A copy of the holiday array indicating additional invalid days.


class numpy.byte[source]

Signed integer type, compatible with C char.  Character code
'b'  Alias on this platform (Linux x86_64)
numpy.int8: 8-bit signed integer (-128 to 127).


numpy.byte_bounds   numpy.byte_bounds(a)[source]

Returns pointers to the end-points of an array.  Parameters

andarray

Input array. It must conform to the Python-side of the array interface.    Returns

(low, high)tuple of 2 integers

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.     Examples >>> I = np.eye(2, dtype='f'); I.dtype
dtype('float32')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
>>> I = np.eye(2); I.dtype
dtype('float64')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True


class numpy.bytes_[source]

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


numpy.c_   numpy.c_ = <numpy.lib.index_tricks.CClass object>

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  column_stack

Stack 1-D arrays as columns into a 2-D array.  r_

For more detailed documentation.    Examples >>> np.c_[np.array([1,2,3]), np.array([4,5,6])]
array([[1, 4],
       [2, 5],
       [3, 6]])
>>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
array([[1, 2, 3, ..., 4, 5, 6]])


numpy.can_cast   numpy.can_cast(from_, to, casting='safe')

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

from_dtype, dtype specifier, scalar, or array

Data type, scalar, or array to cast from.
todtype or dtype specifier

Data type to cast to.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Controls what kind of data casting may occur.  ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done.     Returns

outbool

True if cast can occur according to the casting rule.      See also
dtype, result_type

  Notes  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.  Examples Basic examples >>> np.can_cast(np.int32, np.int64)
True
>>> np.can_cast(np.float64, complex)
True
>>> np.can_cast(complex, float)
False
 >>> np.can_cast('i8', 'f8')
True
>>> np.can_cast('i8', 'f4')
False
>>> np.can_cast('i4', 'S4')
False
 Casting scalars >>> np.can_cast(100, 'i1')
True
>>> np.can_cast(150, 'i1')
False
>>> np.can_cast(150, 'u1')
True
 >>> np.can_cast(3.5e100, np.float32)
False
>>> np.can_cast(1000.0, np.float32)
True
 Array scalar checks the value, array does not >>> np.can_cast(np.array(1000.0), np.float32)
True
>>> np.can_cast(np.array([1000.0]), np.float32)
False
 Using the casting rules >>> np.can_cast('i8', 'i8', 'no')
True
>>> np.can_cast('<i8', '>i8', 'no')
False
 >>> np.can_cast('<i8', '>i8', 'equiv')
True
>>> np.can_cast('<i4', '>i8', 'equiv')
False
 >>> np.can_cast('<i4', '>i8', 'safe')
True
>>> np.can_cast('<i8', '>i4', 'safe')
False
 >>> np.can_cast('<i8', '>i4', 'same_kind')
True
>>> np.can_cast('<i8', '>u4', 'same_kind')
False
 >>> np.can_cast('<i8', '>u4', 'unsafe')
True


numpy.cbrt   numpy.cbrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'cbrt'>

Return the cube-root of an array, element-wise.  New in version 1.10.0.   Parameters

xarray_like

The values whose cube-roots are required.
outndarray, None, or tuple of ndarray and None, optional

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.
wherearray_like, optional

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.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

yndarray

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.     Examples >>> np.cbrt([1,8,27])
array([ 1.,  2.,  3.])


class numpy.cdouble(real=0, imag=0)[source]

Complex number type composed of two double-precision floating-point numbers, compatible with Python complex.  Character code
'D'  Alias
numpy.cfloat  Alias
numpy.complex_  Alias on this platform (Linux x86_64)
numpy.complex128: Complex number type composed of 2 64-bit-precision floating-point numbers.


numpy.ceil   numpy.ceil(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'ceil'>

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\).  Parameters

xarray_like

Input data.
outndarray, None, or tuple of ndarray and None, optional

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.
wherearray_like, optional

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.  **kwargs

For other keyword-only arguments, see the ufunc docs.    Returns

yndarray or scalar

The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.      See also
floor, trunc, rint, fix

  Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.ceil(a)
array([-1., -1., -0.,  1.,  2.,  2.,  2.])


numpy.cfloat[source]

alias of numpy.cdouble


numpy.char.chararray   class numpy.char.chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order=None)[source]

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:  values automatically have whitespace removed from the end when indexed comparison operators automatically remove whitespace from the end when comparing values vectorized string operations are provided as methods (e.g. endswith) and infix operators (e.g. "+", "*", "%")  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”.  Parameters

shapetuple

Shape of the array.
itemsizeint, optional

Length of each array element, in number of characters. Default is 1.
unicodebool, optional

Are the array elements of type unicode (True) or string (False). Default is False.
bufferobject exposing the buffer interface or str, optional

Memory address of the start of the array data. Default is None, in which case a new array is created.
offsetint, optional

Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0.
stridesarray_like of ints, optional

Strides for the array (see ndarray.strides for full description). Default is None.
order{‘C’, ‘F’}, optional

The order in which the array data is stored in memory: ‘C’ -> “row major” order (the default), ‘F’ -> “column major” (Fortran) order.     Examples >>> charar = np.chararray((3, 3))
>>> charar[:] = 'a'
>>> charar
chararray([[b'a', b'a', b'a'],
           [b'a', b'a', b'a'],
           [b'a', b'a', b'a']], dtype='|S1')
 >>> charar = np.chararray(charar.shape, itemsize=5)
>>> charar[:] = 'abc'
>>> charar
chararray([[b'abc', b'abc', b'abc'],
           [b'abc', b'abc', b'abc'],
           [b'abc', b'abc', b'abc']], dtype='|S5')
  Attributes
 T

The transposed array.  base

Base object if memory is from some other object.  ctypes

An object to simplify the interaction of the array with the ctypes module.  data

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

Data-type of the array’s elements.  flags

Information about the memory layout of the array.  flat

A 1-D iterator over the array.  imag

The imaginary part of the array.  itemsize

Length of one array element in bytes.  nbytes

Total bytes consumed by the elements of the array.  ndim

Number of array dimensions.  real

The real part of the array.  shape

Tuple of array dimensions.  size

Number of elements in the array.  strides

Tuple of bytes to step in each dimension when traversing an array.     Methods
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.


numpy.chararray   class numpy.chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order=None)[source]

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:  values automatically have whitespace removed from the end when indexed comparison operators automatically remove whitespace from the end when comparing values vectorized string operations are provided as methods (e.g. endswith) and infix operators (e.g. "+", "*", "%")  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”.  Parameters

shapetuple

Shape of the array.
itemsizeint, optional

Length of each array element, in number of characters. Default is 1.
unicodebool, optional

Are the array elements of type unicode (True) or string (False). Default is False.
bufferobject exposing the buffer interface or str, optional

Memory address of the start of the array data. Default is None, in which case a new array is created.
offsetint, optional

Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0.
stridesarray_like of ints, optional

Strides for the array (see ndarray.strides for full description). Default is None.
order{‘C’, ‘F’}, optional

The order in which the array data is stored in memory: ‘C’ -> “row major” order (the default), ‘F’ -> “column major” (Fortran) order.     Examples >>> charar = np.chararray((3, 3))
>>> charar[:] = 'a'
>>> charar
chararray([[b'a', b'a', b'a'],
           [b'a', b'a', b'a'],
           [b'a', b'a', b'a']], dtype='|S1')
 >>> charar = np.chararray(charar.shape, itemsize=5)
>>> charar[:] = 'abc'
>>> charar
chararray([[b'abc', b'abc', b'abc'],
           [b'abc', b'abc', b'abc'],
           [b'abc', b'abc', b'abc']], dtype='|S5')
  Attributes
 T

The transposed array.  base

Base object if memory is from some other object.  ctypes

An object to simplify the interaction of the array with the ctypes module.  data

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

Data-type of the array’s elements.  flags

Information about the memory layout of the array.  flat

A 1-D iterator over the array.  imag

The imaginary part of the array.  itemsize

Length of one array element in bytes.  nbytes

Total bytes consumed by the elements of the array.  ndim

Number of array dimensions.  real

The real part of the array.  shape

Tuple of array dimensions.  size

Number of elements in the array.  strides

Tuple of bytes to step in each dimension when traversing an array.     Methods
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.


numpy.choose   numpy.choose(a, choices, out=None, mode='raise')[source]

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:  if mode='raise' (the default), then, first of all, each element of a (and thus Ba) must be in the range [0, n-1]; now, suppose that i (in that range) is the value at the (j0, j1, ..., jm) position in Ba - then the value at the same position in the new array is the value in Bchoices[i] at that same position; if mode='wrap', values in a (and thus Ba) may be any (signed) integer; modular arithmetic is used to map integers outside the range [0, n-1] back into that range; and then the new array is constructed as above; if mode='clip', values in a (and thus Ba) may be any (signed) integer; negative integers are mapped to 0; values greater than n-1 are mapped to n-1; and then the new array is constructed as above.   Parameters

aint array

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.
choicessequence of arrays

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”.
outarray, optional

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.
mode{‘raise’ (default), ‘wrap’, ‘clip’}, optional

Specifies how indices outside [0, n-1] will be treated:  ‘raise’ : an exception is raised ‘wrap’ : value becomes value mod n
 ‘clip’ : values < 0 are mapped to 0, values > n-1 are mapped to n-1     Returns

merged_arrayarray

The merged result.    Raises
 ValueError: shape mismatch

If a and each choice array are not all broadcastable to the same shape.      See also  ndarray.choose

equivalent method  numpy.take_along_axis

Preferable if choices is an array    Notes 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. Examples >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
...   [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12,  3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12,  3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20,  1, 12,  3])
>>> # i.e., 0
 A couple examples illustrating how choose broadcasts: >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10,  10],
       [-10,  10, -10],
       [ 10, -10,  10]])
 >>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1,  1,  1,  1,  1],
        [ 2,  2,  2,  2,  2],
        [ 3,  3,  3,  3,  3]],
       [[-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5]]])


numpy.clip   numpy.clip(a, a_min, a_max, out=None, **kwargs)[source]

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

aarray_like

Array containing elements to clip.
a_min, a_maxarray_like or None

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.
outndarray, optional

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.  **kwargs

For other keyword-only arguments, see the ufunc docs.  New in version 1.17.0.     Returns

clipped_arrayndarray

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  Output type determination
  Notes 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. Examples >>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> np.clip(a, 8, 1)
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])


class numpy.clongdouble[source]

Complex number type composed of two extended-precision floating-point numbers.  Character code
'G'  Alias
numpy.clongfloat  Alias
numpy.longcomplex  Alias on this platform (Linux x86_64)
numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.


numpy.clongfloat[source]

alias of numpy.clongdouble


numpy.column_stack   numpy.column_stack(tup)[source]

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

tupsequence of 1-D or 2-D arrays.

Arrays to stack. All of them must have the same first dimension.    Returns

stacked2-D array

The array formed by stacking the given arrays.      See also
stack, hstack, vstack, concatenate

  Examples >>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
       [2, 3],
       [3, 4]])


numpy.common_type   numpy.common_type(*arrays)[source]

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

array1, array2, …ndarrays

Input arrays.    Returns

outdata type code

Data type code.      See also
dtype, mintypecode

  Examples >>> np.common_type(np.arange(2, dtype=np.float32))
<class 'numpy.float32'>
>>> np.common_type(np.arange(2, dtype=np.float32), np.arange(2))
<class 'numpy.float64'>
>>> np.common_type(np.arange(4), np.array([45, 6.j]), np.array([45.0]))
<class 'numpy.complex128'>


numpy.complex128[source]

alias of numpy.cdouble


numpy.complex192
  numpy.complex256[source]

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