numpy.complex64[source]

alias of numpy.csingle


numpy.complex_[source]

alias of numpy.cdouble


numpy.compress   numpy.compress(condition, a, axis=None, out=None)[source]

Return selected slices of an array along given axis. When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. When working on a 1-D array, compress is equivalent to extract.  Parameters

condition1-D array of bools

Array that selects which entries to return. If len(condition) is less than the size of a along the given axis, then output is truncated to the length of the condition array.
aarray_like

Array from which to extract a part.
axisint, optional

Axis along which to take slices. If None (default), work on the flattened array.
outndarray, optional

Output array. Its type is preserved and it must be of the right shape to hold the output.    Returns

compressed_arrayndarray

A copy of a without the slices along axis for which condition is false.      See also
take, choose, diag, diagonal, select

ndarray.compress

Equivalent method in ndarray  extract

Equivalent method when working on 1-D arrays  Output type determination
  Examples >>> a = np.array([[1, 2], [3, 4], [5, 6]])
>>> a
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.compress([0, 1], a, axis=0)
array([[3, 4]])
>>> np.compress([False, True, True], a, axis=0)
array([[3, 4],
       [5, 6]])
>>> np.compress([False, True], a, axis=1)
array([[2],
       [4],
       [6]])
 Working on the flattened array does not return slices along an axis but selects elements. >>> np.compress([False, True], a)
array([2])


numpy.concatenate   numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")

Join a sequence of arrays along an existing axis.  Parameters

a1, a2, …sequence of array_like

The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
axisint, optional

The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.
outndarray, optional

If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified.
dtypestr or dtype

If provided, the destination array will have this dtype. Cannot be provided together with out.  New in version 1.20.0.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Controls what kind of data casting may occur. Defaults to ‘same_kind’.  New in version 1.20.0.     Returns

resndarray

The concatenated array.      See also  ma.concatenate

Concatenate function that preserves input masks.  array_split

Split an array into multiple sub-arrays of equal or near-equal size.  split

Split array into a list of multiple sub-arrays of equal size.  hsplit

Split array into multiple sub-arrays horizontally (column wise).  vsplit

Split array into multiple sub-arrays vertically (row wise).  dsplit

Split array into multiple sub-arrays along the 3rd axis (depth).  stack

Stack a sequence of arrays along a new axis.  block

Assemble arrays from blocks.  hstack

Stack arrays in sequence horizontally (column wise).  vstack

Stack arrays in sequence vertically (row wise).  dstack

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

Stack 1-D arrays as columns into a 2-D array.    Notes When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead. Examples >>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
       [3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
 This function will not preserve masking of MaskedArray inputs. >>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data=[0, --, 2],
             mask=[False,  True, False],
       fill_value=999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data=[0, 1, 2, 2, 3, 4],
             mask=False,
       fill_value=999999)
>>> np.ma.concatenate([a, b])
masked_array(data=[0, --, 2, 2, 3, 4],
             mask=[False,  True, False, False, False, False],
       fill_value=999999)


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

Return the complex conjugate, element-wise. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.  Parameters

xarray_like

Input value.
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

The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar.     Notes conj is an alias for conjugate: >>> np.conj is np.conjugate
True
 Examples >>> np.conjugate(1+2j)
(1-2j)
 >>> x = np.eye(2) + 1j * np.eye(2)
>>> np.conjugate(x)
array([[ 1.-1.j,  0.-0.j],
       [ 0.-0.j,  1.-1.j]])


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

Return the complex conjugate, element-wise. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.  Parameters

xarray_like

Input value.
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

The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar.     Notes conj is an alias for conjugate: >>> np.conj is np.conjugate
True
 Examples >>> np.conjugate(1+2j)
(1-2j)
 >>> x = np.eye(2) + 1j * np.eye(2)
>>> np.conjugate(x)
array([[ 1.-1.j,  0.-0.j],
       [ 0.-0.j,  1.-1.j]])


numpy.convolve   numpy.convolve(a, v, mode='full')[source]

Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If v is longer than a, the arrays are swapped before computation.  Parameters

a(N,) array_like

First one-dimensional input array.
v(M,) array_like

Second one-dimensional input array.
mode{‘full’, ‘valid’, ‘same’}, optional

 ‘full’:

By default, mode is ‘full’. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen.  ‘same’:

Mode ‘same’ returns output of length max(M, N). Boundary effects are still visible.  ‘valid’:

Mode ‘valid’ returns output of length max(M, N) - min(M, N) + 1. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect.      Returns

outndarray

Discrete, linear convolution of a and v.      See also  scipy.signal.fftconvolve

Convolve two arrays using the Fast Fourier Transform.  scipy.linalg.toeplitz

Used to construct the convolution operator.  polymul

Polynomial multiplication. Same output as convolve, but also accepts poly1d objects as input.    Notes The discrete convolution operation is defined as  \[(a * v)[n] = \sum_{m = -\infty}^{\infty} a[m] v[n - m]\] It can be shown that a convolution \(x(t) * y(t)\) in time/space is equivalent to the multiplication \(X(f) Y(f)\) in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function scipy.signal.fftconvolve exploits the FFT to calculate the convolution of large data-sets. References  1
Wikipedia, “Convolution”, https://en.wikipedia.org/wiki/Convolution   Examples Note how the convolution operator flips the second array before “sliding” the two across one another: >>> np.convolve([1, 2, 3], [0, 1, 0.5])
array([0. , 1. , 2.5, 4. , 1.5])
 Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account: >>> np.convolve([1,2,3],[0,1,0.5], 'same')
array([1. ,  2.5,  4. ])
 The two arrays are of the same length, so there is only one position where they completely overlap: >>> np.convolve([1,2,3],[0,1,0.5], 'valid')
array([2.5])


numpy.copy   numpy.copy(a, order='K', subok=False)[source]

Return an array copy of the given object.  Parameters

aarray_like

Input data.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.)
subokbool, optional

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (defaults to False).  New in version 1.19.0.     Returns

arrndarray

Array interpretation of a.      See also  ndarray.copy

Preferred method for creating an array copy    Notes This is equivalent to: >>> np.array(a, copy=True)
 Examples Create an array x, with a reference y and a copy z: >>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
 Note that, when we modify x, y changes, but not z: >>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
 Note that, np.copy clears previously set WRITEABLE=False flag. >>> a = np.array([1, 2, 3])
>>> a.flags["WRITEABLE"] = False
>>> b = np.copy(a)
>>> b.flags["WRITEABLE"]
True
>>> b[0] = 3
>>> b
array([3, 2, 3])
 Note that np.copy is a shallow copy and will not copy object elements within arrays. This is mainly important for arrays containing Python objects. The new array will contain the same object which may lead to surprises if that object can be modified (is mutable): >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = np.copy(a)
>>> b[2][0] = 10
>>> a
array([1, 'm', list([10, 3, 4])], dtype=object)
 To ensure all elements within an object array are copied, use copy.deepcopy: >>> import copy
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> c = copy.deepcopy(a)
>>> c[2][0] = 10
>>> c
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)


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

Change the sign of x1 to that of x2, element-wise. If x2 is a scalar, its sign will be copied to all elements of x1.  Parameters

x1array_like

Values to change the sign of.
x2array_like

The sign of x2 is copied to x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
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

The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.     Examples >>> np.copysign(1.3, -1)
-1.3
>>> 1/np.copysign(0, 1)
inf
>>> 1/np.copysign(0, -1)
-inf
 >>> np.copysign([-1, 0, 1], -1.1)
array([-1., -0., -1.])
>>> np.copysign([-1, 0, 1], np.arange(3)-1)
array([-1.,  0.,  1.])


numpy.copyto   numpy.copyto(dst, src, casting='same_kind', where=True)

Copies values from one array to another, broadcasting as necessary. Raises a TypeError if the casting rule is violated, and if where is provided, it selects which elements to copy.  New in version 1.7.0.   Parameters

dstndarray

The array into which values are copied.
srcarray_like

The array from which values are copied.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Controls what kind of data casting may occur when copying.  ‘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.
wherearray_like of bool, optional

A boolean array which is broadcasted to match the dimensions of dst, and selects elements to copy from src to dst wherever it contains the value True.


numpy.corrcoef   numpy.corrcoef(x, y=None, rowvar=True, bias=<no value>, ddof=<no value>, *, dtype=None)[source]

Return Pearson product-moment correlation coefficients. Please refer to the documentation for cov for more detail. The relationship between the correlation coefficient matrix, R, and the covariance matrix, C, is  \[R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }\] The values of R are between -1 and 1, inclusive.  Parameters

xarray_like

A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables. Also see rowvar below.
yarray_like, optional

An additional set of variables and observations. y has the same shape as x.
rowvarbool, optional

If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.
bias_NoValue, optional

Has no effect, do not use.  Deprecated since version 1.10.0.
ddof_NoValue, optional

Has no effect, do not use.  Deprecated since version 1.10.0.
dtypedata-type, optional

Data-type of the result. By default, the return data-type will have at least numpy.float64 precision.  New in version 1.20.     Returns

Rndarray

The correlation coefficient matrix of the variables.      See also  cov

Covariance matrix    Notes Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case. This function accepts but discards arguments bias and ddof. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy. Examples In this example we generate two random arrays, xarr and yarr, and compute the row-wise and column-wise Pearson correlation coefficients, R. Since rowvar is true by default, we first find the row-wise Pearson correlation coefficients between the variables of xarr. >>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> xarr = rng.random((3, 3))
>>> xarr
array([[0.77395605, 0.43887844, 0.85859792],
       [0.69736803, 0.09417735, 0.97562235],
       [0.7611397 , 0.78606431, 0.12811363]])
>>> R1 = np.corrcoef(xarr)
>>> R1
array([[ 1.        ,  0.99256089, -0.68080986],
       [ 0.99256089,  1.        , -0.76492172],
       [-0.68080986, -0.76492172,  1.        ]])
 If we add another set of variables and observations yarr, we can compute the row-wise Pearson correlation coefficients between the variables in xarr and yarr. >>> yarr = rng.random((3, 3))
>>> yarr
array([[0.45038594, 0.37079802, 0.92676499],
       [0.64386512, 0.82276161, 0.4434142 ],
       [0.22723872, 0.55458479, 0.06381726]])
>>> R2 = np.corrcoef(xarr, yarr)
>>> R2
array([[ 1.        ,  0.99256089, -0.68080986,  0.75008178, -0.934284  ,
        -0.99004057],
       [ 0.99256089,  1.        , -0.76492172,  0.82502011, -0.97074098,
        -0.99981569],
       [-0.68080986, -0.76492172,  1.        , -0.99507202,  0.89721355,
         0.77714685],
       [ 0.75008178,  0.82502011, -0.99507202,  1.        , -0.93657855,
        -0.83571711],
       [-0.934284  , -0.97074098,  0.89721355, -0.93657855,  1.        ,
         0.97517215],
       [-0.99004057, -0.99981569,  0.77714685, -0.83571711,  0.97517215,
         1.        ]])
 Finally if we use the option rowvar=False, the columns are now being treated as the variables and we will find the column-wise Pearson correlation coefficients between variables in xarr and yarr. >>> R3 = np.corrcoef(xarr, yarr, rowvar=False)
>>> R3
array([[ 1.        ,  0.77598074, -0.47458546, -0.75078643, -0.9665554 ,
         0.22423734],
       [ 0.77598074,  1.        , -0.92346708, -0.99923895, -0.58826587,
        -0.44069024],
       [-0.47458546, -0.92346708,  1.        ,  0.93773029,  0.23297648,
         0.75137473],
       [-0.75078643, -0.99923895,  0.93773029,  1.        ,  0.55627469,
         0.47536961],
       [-0.9665554 , -0.58826587,  0.23297648,  0.55627469,  1.        ,
        -0.46666491],
       [ 0.22423734, -0.44069024,  0.75137473,  0.47536961, -0.46666491,
         1.        ]])


numpy.correlate   numpy.correlate(a, v, mode='valid')[source]

Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts: c_{av}[k] = sum_n a[n+k] * conj(v[n])
 with a and v sequences being zero-padded where necessary and conj being the conjugate.  Parameters

a, varray_like

Input sequences.
mode{‘valid’, ‘same’, ‘full’}, optional

Refer to the convolve docstring. Note that the default is ‘valid’, unlike convolve, which uses ‘full’.
old_behaviorbool

old_behavior was removed in NumPy 1.10. If you need the old behavior, use multiarray.correlate.    Returns

outndarray

Discrete cross-correlation of a and v.      See also  convolve

Discrete, linear convolution of two one-dimensional sequences.  multiarray.correlate

Old, no conjugate, version of correlate.  scipy.signal.correlate

uses FFT which has superior performance on large arrays.    Notes The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is: c'_{av}[k] = sum_n a[n] conj(v[n+k])
 which is related to c_{av}[k] by c'_{av}[k] = c_{av}[-k]. numpy.correlate may perform slowly in large arrays (i.e. n = 1e5) because it does not use the FFT to compute the convolution; in that case, scipy.signal.correlate might be preferable. Examples >>> np.correlate([1, 2, 3], [0, 1, 0.5])
array([3.5])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
array([2. ,  3.5,  3. ])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
array([0.5,  2. ,  3.5,  3. ,  0. ])
 Using complex sequences: >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
array([ 0.5-0.5j,  1.0+0.j ,  1.5-1.5j,  3.0-1.j ,  0.0+0.j ])
 Note that you get the time reversed, complex conjugated result when the two input sequences change places, i.e., c_{va}[k] = c^{*}_{av}[-k]: >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
array([ 0.0+0.j ,  3.0+1.j ,  1.5+1.5j,  1.0+0.j ,  0.5+0.5j])


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

Cosine element-wise.  Parameters

xarray_like

Input array in radians.
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

The corresponding cosine values. This is a scalar if x is a scalar.     Notes If out is provided, the function writes the result into it, and returns a reference to out. (See Examples) References M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972. Examples >>> np.cos(np.array([0, np.pi/2, np.pi]))
array([  1.00000000e+00,   6.12303177e-17,  -1.00000000e+00])
>>>
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.cos([0.1], out1)
>>> out2 is out1
True
>>>
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)


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

Hyperbolic cosine, element-wise. Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j*x).  Parameters

xarray_like

Input array.
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

Output array of same shape as x. This is a scalar if x is a scalar.     Examples >>> np.cosh(0)
1.0
 The hyperbolic cosine describes the shape of a hanging cable: >>> import matplotlib.pyplot as plt
>>> x = np.linspace(-4, 4, 1000)
>>> plt.plot(x, np.cosh(x))
>>> plt.show()


numpy.count_nonzero   numpy.count_nonzero(a, axis=None, *, keepdims=False)[source]

Counts the number of non-zero values in the array a. The word “non-zero” is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object’s “truthfulness”. For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True.  Parameters

aarray_like

The array for which to count non-zeros.
axisint or tuple, optional

Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of a.  New in version 1.12.0.
keepdimsbool, optional

If this is set to True, the axes that are counted are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.  New in version 1.19.0.     Returns

countint or array of int

Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.      See also  nonzero

Return the coordinates of all the non-zero values.    Examples >>> np.count_nonzero(np.eye(4))
4
>>> a = np.array([[0, 1, 7, 0],
...               [3, 0, 2, 19]])
>>> np.count_nonzero(a)
5
>>> np.count_nonzero(a, axis=0)
array([1, 1, 2, 1])
>>> np.count_nonzero(a, axis=1)
array([2, 3])
>>> np.count_nonzero(a, axis=1, keepdims=True)
array([[2],
       [3]])


numpy.cov   numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None)[source]

Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, \(X = [x_1, x_2, ... x_N]^T\), then the covariance matrix element \(C_{ij}\) is the covariance of \(x_i\) and \(x_j\). The element \(C_{ii}\) is the variance of \(x_i\). See the notes for an outline of the algorithm.  Parameters

marray_like

A 1-D or 2-D array containing multiple variables and observations. Each row of m represents a variable, and each column a single observation of all those variables. Also see rowvar below.
yarray_like, optional

An additional set of variables and observations. y has the same form as that of m.
rowvarbool, optional

If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.
biasbool, optional

Default normalization (False) is by (N - 1), where N is the number of observations given (unbiased estimate). If bias is True, then normalization is by N. These values can be overridden by using the keyword ddof in numpy versions >= 1.5.
ddofint, optional

If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified, and ddof=0 will return the simple average. See the notes for the details. The default value is None.  New in version 1.5.
fweightsarray_like, int, optional

1-D array of integer frequency weights; the number of times each observation vector should be repeated.  New in version 1.10.
aweightsarray_like, optional

1-D array of observation vector weights. These relative weights are typically large for observations considered “important” and smaller for observations considered less “important”. If ddof=0 the array of weights can be used to assign probabilities to observation vectors.  New in version 1.10.
dtypedata-type, optional

Data-type of the result. By default, the return data-type will have at least numpy.float64 precision.  New in version 1.20.     Returns

outndarray

The covariance matrix of the variables.      See also  corrcoef

Normalized covariance matrix    Notes Assume that the observations are in the columns of the observation array m and let f = fweights and a = aweights for brevity. The steps to compute the weighted covariance are as follows: >>> m = np.arange(10, dtype=np.float64)
>>> f = np.arange(10) * 2
>>> a = np.arange(10) ** 2.
>>> ddof = 1
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=None, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
 Note that when a == 1, the normalization factor v1 / (v1**2 - ddof * v2) goes over to 1 / (np.sum(f) - ddof) as it should. Examples Consider two variables, \(x_0\) and \(x_1\), which correlate perfectly, but in opposite directions: >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
       [2, 1, 0]])
 Note how \(x_0\) increases while \(x_1\) decreases. The covariance matrix shows this clearly: >>> np.cov(x)
array([[ 1., -1.],
       [-1.,  1.]])
 Note that element \(C_{0,1}\), which shows the correlation between \(x_0\) and \(x_1\), is negative. Further, note how x and y are combined: >>> x = [-2.1, -1,  4.3]
>>> y = [3,  1.1,  0.12]
>>> X = np.stack((x, y), axis=0)
>>> np.cov(X)
array([[11.71      , -4.286     ], # may vary
       [-4.286     ,  2.144133]])
>>> np.cov(x, y)
array([[11.71      , -4.286     ], # may vary
       [-4.286     ,  2.144133]])
>>> np.cov(x)
array(11.71)


numpy.cross   numpy.cross(a, b, axisa=- 1, axisb=- 1, axisc=- 1, axis=None)[source]

Return the cross product of two (arrays of) vectors. The cross product of a and b in \(R^3\) is a vector perpendicular to both a and b. If a and b are arrays of vectors, the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Where the dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned.  Parameters

aarray_like

Components of the first vector(s).
barray_like

Components of the second vector(s).
axisaint, optional

Axis of a that defines the vector(s). By default, the last axis.
axisbint, optional

Axis of b that defines the vector(s). By default, the last axis.
axiscint, optional

Axis of c containing the cross product vector(s). Ignored if both input vectors have dimension 2, as the return is scalar. By default, the last axis.
axisint, optional

If defined, the axis of a, b and c that defines the vector(s) and cross product(s). Overrides axisa, axisb and axisc.    Returns

cndarray

Vector cross product(s).    Raises
 ValueError

When the dimension of the vector(s) in a and/or b does not equal 2 or 3.      See also  inner

Inner product  outer

Outer product.  ix_

Construct index arrays.    Notes  New in version 1.9.0.  Supports full broadcasting of the inputs. Examples Vector cross-product. >>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([-3,  6, -3])
 One vector with dimension 2. >>> x = [1, 2]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
 Equivalently: >>> x = [1, 2, 0]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
 Both vectors with dimension 2. >>> x = [1,2]
>>> y = [4,5]
>>> np.cross(x, y)
array(-3)
 Multiple vector cross-products. Note that the direction of the cross product vector is defined by the right-hand rule. >>> x = np.array([[1,2,3], [4,5,6]])
>>> y = np.array([[4,5,6], [1,2,3]])
>>> np.cross(x, y)
array([[-3,  6, -3],
       [ 3, -6,  3]])
 The orientation of c can be changed using the axisc keyword. >>> np.cross(x, y, axisc=0)
array([[-3,  3],
       [ 6, -6],
       [-3,  3]])
 Change the vector definition of x and y using axisa and axisb. >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
>>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
>>> np.cross(x, y)
array([[ -6,  12,  -6],
       [  0,   0,   0],
       [  6, -12,   6]])
>>> np.cross(x, y, axisa=0, axisb=0)
array([[-24,  48, -24],
       [-30,  60, -30],
       [-36,  72, -36]])


class numpy.csingle[source]

Complex number type composed of two single-precision floating-point numbers.  Character code
'F'  Alias
numpy.singlecomplex  Alias on this platform (Linux x86_64)
numpy.complex64: Complex number type composed of 2 32-bit-precision floating-point numbers.


C-Types Foreign Function Interface (numpy.ctypeslib)   numpy.ctypeslib.as_array(obj, shape=None)[source]

Create a numpy array from a ctypes array or POINTER. The numpy array shares the memory with the ctypes object. The shape parameter must be given if converting from a ctypes POINTER. The shape parameter is ignored if converting from a ctypes array
   numpy.ctypeslib.as_ctypes(obj)[source]

Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.
   numpy.ctypeslib.as_ctypes_type(dtype)[source]

Convert a dtype into a ctypes type.  Parameters

dtypedtype

The dtype to convert    Returns
 ctype

A ctype scalar, union, array, or struct    Raises
 NotImplementedError

If the conversion is not possible     Notes This function does not losslessly round-trip in either direction. np.dtype(as_ctypes_type(dt)) will:  insert padding fields reorder fields to be sorted by offset discard field titles  as_ctypes_type(np.dtype(ctype)) will:  discard the class names of ctypes.Structures and ctypes.Unions convert single-element ctypes.Unions into single-element ctypes.Structures insert padding fields
   numpy.ctypeslib.load_library(libname, loader_path)[source]

It is possible to load a library using >>> lib = ctypes.cdll[<full_path_name>]
 But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. NumPy supplies the load_library function as a convenience.  Changed in version 1.20.0: Allow libname and loader_path to take any path-like object.   Parameters

libnamepath-like

Name of the library, which can have ‘lib’ as a prefix, but without an extension.
loader_pathpath-like

Where the library can be found.    Returns

ctypes.cdll[libpath]library object

A ctypes library object    Raises
 OSError

If there is no library with the expected extension, or the library is defective and cannot be loaded.
   numpy.ctypeslib.ndpointer(dtype=None, ndim=None, shape=None, flags=None)[source]

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

dtypedata-type, optional

Array data-type.
ndimint, optional

Number of array dimensions.
shapetuple of ints, optional

Array shape.
flagsstr or tuple of str

Array flags; may be one or more of:  C_CONTIGUOUS / C / CONTIGUOUS F_CONTIGUOUS / F / FORTRAN OWNDATA / O WRITEABLE / W ALIGNED / A WRITEBACKIFCOPY / X UPDATEIFCOPY / U     Returns

klassndpointer type object

A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags information.    Raises
 TypeError

If a given array does not satisfy the specified restrictions.     Examples >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
...                                                  ndim=1,
...                                                  flags='C_CONTIGUOUS')]
...
>>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
...

   class numpy.ctypeslib.c_intp

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


numpy.ctypeslib.as_ctypes(obj)[source]

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


numpy.ctypeslib.as_ctypes_type(dtype)[source]

Convert a dtype into a ctypes type.  Parameters

dtypedtype

The dtype to convert    Returns
 ctype

A ctype scalar, union, array, or struct    Raises
 NotImplementedError

If the conversion is not possible     Notes This function does not losslessly round-trip in either direction. np.dtype(as_ctypes_type(dt)) will:  insert padding fields reorder fields to be sorted by offset discard field titles  as_ctypes_type(np.dtype(ctype)) will:  discard the class names of ctypes.Structures and ctypes.Unions convert single-element ctypes.Unions into single-element ctypes.Structures insert padding fields


class numpy.ctypeslib.c_intp

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


numpy.ctypeslib.load_library(libname, loader_path)[source]

It is possible to load a library using >>> lib = ctypes.cdll[<full_path_name>]
 But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. NumPy supplies the load_library function as a convenience.  Changed in version 1.20.0: Allow libname and loader_path to take any path-like object.   Parameters

libnamepath-like

Name of the library, which can have ‘lib’ as a prefix, but without an extension.
loader_pathpath-like

Where the library can be found.    Returns

ctypes.cdll[libpath]library object

A ctypes library object    Raises
 OSError

If there is no library with the expected extension, or the library is defective and cannot be loaded.


numpy.ctypeslib.ndpointer(dtype=None, ndim=None, shape=None, flags=None)[source]

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

dtypedata-type, optional

Array data-type.
ndimint, optional

Number of array dimensions.
shapetuple of ints, optional

Array shape.
flagsstr or tuple of str

Array flags; may be one or more of:  C_CONTIGUOUS / C / CONTIGUOUS F_CONTIGUOUS / F / FORTRAN OWNDATA / O WRITEABLE / W ALIGNED / A WRITEBACKIFCOPY / X UPDATEIFCOPY / U     Returns

klassndpointer type object

A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags information.    Raises
 TypeError

If a given array does not satisfy the specified restrictions.     Examples >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
...                                                  ndim=1,
...                                                  flags='C_CONTIGUOUS')]
...
>>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
...


numpy.cumprod   numpy.cumprod(a, axis=None, dtype=None, out=None)[source]

Return the cumulative product of elements along a given axis.  Parameters

aarray_like

Input array.
axisint, optional

Axis along which the cumulative product is computed. By default the input is flattened.
dtypedtype, optional

Type of the returned array, as well as of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead.
outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type of the resulting values will be cast if necessary.    Returns

cumprodndarray

A new array holding the result is returned unless out is specified, in which case a reference to out is returned.      See also  Output type determination
  Notes Arithmetic is modular when using integer types, and no error is raised on overflow. Examples >>> a = np.array([1,2,3])
>>> np.cumprod(a) # intermediate results 1, 1*2
...               # total product 1*2*3 = 6
array([1, 2, 6])
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.cumprod(a, dtype=float) # specify type of output
array([   1.,    2.,    6.,   24.,  120.,  720.])
 The cumulative product for each column (i.e., over the rows) of a: >>> np.cumprod(a, axis=0)
array([[ 1,  2,  3],
       [ 4, 10, 18]])
 The cumulative product for each row (i.e. over the columns) of a: >>> np.cumprod(a,axis=1)
array([[  1,   2,   6],
       [  4,  20, 120]])


numpy.cumsum   numpy.cumsum(a, axis=None, dtype=None, out=None)[source]

Return the cumulative sum of the elements along a given axis.  Parameters

aarray_like

Input array.
axisint, optional

Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
dtypedtype, optional

Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.
outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. See Output type determination for more details.    Returns

cumsum_along_axisndarray.

A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.      See also  sum

Sum array elements.  trapz

Integration of array values using the composite trapezoidal rule.  diff

Calculate the n-th discrete difference along given axis.    Notes Arithmetic is modular when using integer types, and no error is raised on overflow. cumsum(a)[-1] may not be equal to sum(a) for floating-point values since sum may use a pairwise summation routine, reducing the roundoff-error. See sum for more information. Examples >>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.cumsum(a)
array([ 1,  3,  6, 10, 15, 21])
>>> np.cumsum(a, dtype=float)     # specifies type of output value(s)
array([  1.,   3.,   6.,  10.,  15.,  21.])
 >>> np.cumsum(a,axis=0)      # sum over rows for each of the 3 columns
array([[1, 2, 3],
       [5, 7, 9]])
>>> np.cumsum(a,axis=1)      # sum over columns for each of the 2 rows
array([[ 1,  3,  6],
       [ 4,  9, 15]])
 cumsum(b)[-1] may not be equal to sum(b) >>> b = np.array([1, 2e-9, 3e-9] * 1000000)
>>> b.cumsum()[-1]
1000000.0050045159
>>> b.sum()
1000000.0050000029


numpy.DataSource   class numpy.DataSource(destpath='.')[source]

A generic data source file (file, http, ftp, …). DataSources can be local files or remote files/URLs. The files may also be compressed or uncompressed. DataSource hides some of the low-level details of downloading the file, allowing you to simply pass in a valid file path (or URL) and obtain a file object.  Parameters

destpathstr or None, optional

Path to the directory where the source file gets downloaded to for use. If destpath is None, a temporary directory will be created. The default path is the current directory.     Notes URLs require a scheme string (http://) to be used, without it they will fail: >>> repos = np.DataSource()
>>> repos.exists('www.google.com/index.html')
False
>>> repos.exists('http://www.google.com/index.html')
True
 Temporary directories are deleted when the DataSource is deleted. Examples >>> ds = np.DataSource('/home/guido')
>>> urlname = 'http://www.google.com/'
>>> gfile = ds.open('http://www.google.com/')
>>> ds.abspath(urlname)
'/home/guido/www.google.com/index.html'

>>> ds = np.DataSource(None)  # use with temporary file
>>> ds.open('/home/guido/foobar.txt')
<open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430>
>>> ds.abspath('/home/guido/foobar.txt')
'/tmp/.../home/guido/foobar.txt'
 Methods
abspath(path) Return absolute path of file in the DataSource directory.
exists(path) Test if path exists.
open(path[, mode, encoding, newline]) Open and return file-like object.


class numpy.datetime64[source]

If created from a 64-bit integer, it represents an offset from 1970-01-01T00:00:00. If created from string, the string can be in ISO 8601 date or datetime format. >>> np.datetime64(10, 'Y')
numpy.datetime64('1980')
>>> np.datetime64('1980', 'Y')
numpy.datetime64('1980')
>>> np.datetime64(10, 'D')
numpy.datetime64('1970-01-11')
 See Datetimes and Timedeltas for more information.  Character code
'M'


numpy.datetime_as_string   numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')

Convert an array of datetimes into an array of strings.  Parameters

arrarray_like of datetime64

The array of UTC timestamps to format.
unitstr

One of None, ‘auto’, or a datetime unit.
timezone{‘naive’, ‘UTC’, ‘local’} or tzinfo

Timezone information to use when displaying the datetime. If ‘UTC’, end with a Z to indicate UTC time. If ‘local’, convert to the local timezone first, and suffix with a +-#### timezone offset. If a tzinfo object, then do as with ‘local’, but use the specified timezone.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}

Casting to allow when changing between datetime units.    Returns

str_arrndarray

An array of strings the same shape as arr.     Examples >>> import pytz
>>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
>>> d
array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
       '2002-10-27T07:30'], dtype='datetime64[m]')
 Setting the timezone to UTC shows the same information, but with a Z suffix >>> np.datetime_as_string(d, timezone='UTC')
array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
       '2002-10-27T07:30Z'], dtype='<U35')
 Note that we picked datetimes that cross a DST boundary. Passing in a pytz timezone object will print the appropriate offset >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
       '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
 Passing in a unit will change the precision >>> np.datetime_as_string(d, unit='h')
array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
      dtype='<U32')
>>> np.datetime_as_string(d, unit='s')
array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
       '2002-10-27T07:30:00'], dtype='<U38')
 ‘casting’ can be used to specify whether precision can be changed >>> np.datetime_as_string(d, unit='h', casting='safe')
Traceback (most recent call last):
    ...
TypeError: Cannot create a datetime string as units 'h' from a NumPy
datetime with units 'm' according to the rule 'safe'


numpy.datetime_data   numpy.datetime_data(dtype, /)

Get information about the step size of a date or time type. The returned tuple can be passed as the second argument of numpy.datetime64 and numpy.timedelta64.  Parameters

dtypedtype

The dtype object, which must be a datetime64 or timedelta64 type.    Returns

unitstr

The datetime unit on which this dtype is based.
countint

The number of base units in a step.     Examples >>> dt_25s = np.dtype('timedelta64[25s]')
>>> np.datetime_data(dt_25s)
('s', 25)
>>> np.array(10, dt_25s).astype('timedelta64[s]')
array(250, dtype='timedelta64[s]')
 The result can be used to construct a datetime that uses the same units as a timedelta >>> np.datetime64('2010', np.datetime_data(dt_25s))
numpy.datetime64('2010-01-01T00:00:00','25s')


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

Convert angles from degrees to radians.  Parameters

xarray_like

Angles in degrees.
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

The corresponding angle in radians. This is a scalar if x is a scalar.      See also  rad2deg

Convert angles from radians to degrees.  unwrap

Remove large jumps in angle by wrapping.    Notes  New in version 1.3.0.  deg2rad(x) is x * pi / 180. Examples >>> np.deg2rad(180)
3.1415926535897931


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

Convert angles from radians to degrees.  Parameters

xarray_like

Input array in radians.
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 of floats

The corresponding degree values; if out was supplied this is a reference to it. This is a scalar if x is a scalar.      See also  rad2deg

equivalent function    Examples Convert a radian array to degrees >>> rad = np.arange(12.)*np.pi/6
>>> np.degrees(rad)
array([   0.,   30.,   60.,   90.,  120.,  150.,  180.,  210.,  240.,
        270.,  300.,  330.])
 >>> out = np.zeros((rad.shape))
>>> r = np.degrees(rad, out)
>>> np.all(r == out)
True


numpy.delete   numpy.delete(arr, obj, axis=None)[source]

Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj].  Parameters

arrarray_like

Input array.
objslice, int or array of ints

Indicate indices of sub-arrays to remove along the specified axis.  Changed in version 1.19.0: Boolean indices are now treated as a mask of elements to remove, rather than being cast to the integers 0 and 1.
axisint, optional

The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.    Returns

outndarray

A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.      See also  insert

Insert elements into an array.  append

Append elements at the end of an array.    Notes Often it is preferable to use a boolean mask. For example: >>> arr = np.arange(12) + 1
>>> mask = np.ones(len(arr), dtype=bool)
>>> mask[[0,2,4]] = False
>>> result = arr[mask,...]
 Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further use of mask. Examples >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> arr
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])
 >>> np.delete(arr, np.s_[::2], 1)
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])


numpy.deprecate   numpy.deprecate(*args, **kwargs)[source]

Issues a DeprecationWarning, adds warning to old_name’s docstring, rebinds old_name.__name__ and returns the new function object. This function may also be used as a decorator.  Parameters

funcfunction

The function to be deprecated.
old_namestr, optional

The name of the function to be deprecated. Default is None, in which case the name of func is used.
new_namestr, optional

The new name for the function. Default is None, in which case the deprecation message is that old_name is deprecated. If given, the deprecation message is that old_name is deprecated and new_name should be used instead.
messagestr, optional

Additional explanation of the deprecation. Displayed in the docstring after the warning.    Returns

old_funcfunction

The deprecated function.     Examples Note that olduint returns a value after printing Deprecation Warning: >>> olduint = np.deprecate(np.uint)
DeprecationWarning: `uint64` is deprecated! # may vary
>>> olduint(6)
6


numpy.deprecate_with_doc   numpy.deprecate_with_doc(msg)[source]

Deprecates a function and includes the deprecation in its docstring. This function is used as a decorator. It returns an object that can be used to issue a DeprecationWarning, by passing the to-be decorated function as argument, this adds warning to the to-be decorated function’s docstring and returns the new function object.  Parameters

msgstr

Additional explanation of the deprecation. Displayed in the docstring after the warning.    Returns

objobject

    See also  deprecate

Decorate a function such that it issues a DeprecationWarning


numpy.diag   numpy.diag(v, k=0)[source]

Extract a diagonal or construct a diagonal array. See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using.  Parameters

varray_like

If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.
kint, optional

Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.    Returns

outndarray

The extracted diagonal or constructed diagonal array.      See also  diagonal

Return specified diagonals.  diagflat

Create a 2-D array with the flattened input as a diagonal.  trace

Sum along diagonals.  triu

Upper triangle of an array.  tril

Lower triangle of an array.    Examples >>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
 >>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
 >>> np.diag(np.diag(x))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])


numpy.diag_indices   numpy.diag_indices(n, ndim=2)[source]

Return the indices to access the main diagonal of an array. This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2 dimensions and shape (n, n, …, n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is the set of indices to access a[i, i, ..., i] for i = [0..n-1].  Parameters

nint

The size, along each dimension, of the arrays for which the returned indices can be used.
ndimint, optional

The number of dimensions.      See also  diag_indices_from
  Notes  New in version 1.4.0.  Examples Create a set of indices to access the diagonal of a (4, 4) array: >>> di = np.diag_indices(4)
>>> di
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> a[di] = 100
>>> a
array([[100,   1,   2,   3],
       [  4, 100,   6,   7],
       [  8,   9, 100,  11],
       [ 12,  13,  14, 100]])
 Now, we create indices to manipulate a 3-D array: >>> d3 = np.diag_indices(2, 3)
>>> d3
(array([0, 1]), array([0, 1]), array([0, 1]))
 And use it to set the diagonal of an array of zeros to 1: >>> a = np.zeros((2, 2, 2), dtype=int)
>>> a[d3] = 1
>>> a
array([[[1, 0],
        [0, 0]],
       [[0, 0],
        [0, 1]]])


numpy.diag_indices_from   numpy.diag_indices_from(arr)[source]

Return the indices to access the main diagonal of an n-dimensional array. See diag_indices for full details.  Parameters

arrarray, at least 2-D

    See also  diag_indices
  Notes  New in version 1.4.0.


numpy.diagflat   numpy.diagflat(v, k=0)[source]

Create a two-dimensional array with the flattened input as a diagonal.  Parameters

varray_like

Input data, which is flattened and set as the k-th diagonal of the output.
kint, optional

Diagonal to set; 0, the default, corresponds to the “main” diagonal, a positive (negative) k giving the number of the diagonal above (below) the main.    Returns

outndarray

The 2-D output array.      See also  diag

MATLAB work-alike for 1-D and 2-D arrays.  diagonal

Return specified diagonals.  trace

Sum along diagonals.    Examples >>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
 >>> np.diagflat([1,2], 1)
array([[0, 1, 0],
       [0, 0, 2],
       [0, 0, 0]])


numpy.diagonal   numpy.diagonal(a, offset=0, axis1=0, axis2=1)[source]

Return specified diagonals. If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals. In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy of the values in the diagonal. In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal, but depending on this fact is deprecated. Writing to the resulting array continues to work as it used to, but a FutureWarning is issued. Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error. In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array. If you don’t write to the array returned by this function, then you can just ignore all of the above. If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a). This will work with both past and future versions of NumPy.  Parameters

aarray_like

Array from which the diagonals are taken.
offsetint, optional

Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0).
axis1int, optional

Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).
axis2int, optional

Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1).    Returns

array_of_diagonalsndarray

If a is 2-D, then a 1-D array containing the diagonal and of the same type as a is returned unless a is a matrix, in which case a 1-D array rather than a (2-D) matrix is returned in order to maintain backward compatibility. If a.ndim > 2, then the dimensions specified by axis1 and axis2 are removed, and a new axis inserted at the end corresponding to the diagonal.    Raises
 ValueError

If the dimension of a is less than 2.      See also  diag

MATLAB work-a-like for 1-D and 2-D arrays.  diagflat

Create diagonal arrays.  trace

Sum along diagonals.    Examples >>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])
 A 3-D example: >>> a = np.arange(8).reshape(2,2,2); a
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> a.diagonal(0,  # Main diagonals of two arrays created by skipping
...            0,  # across the outer(left)-most axis last and
...            1)  # the "middle" (row) axis first.
array([[0, 6],
       [1, 7]])
 The sub-arrays whose main diagonals we just obtained; note that each corresponds to fixing the right-most (column) axis, and that the diagonals are “packed” in rows. >>> a[:,:,0]  # main diagonal is [0 6]
array([[0, 2],
       [4, 6]])
>>> a[:,:,1]  # main diagonal is [1 7]
array([[1, 3],
       [5, 7]])
 The anti-diagonal can be obtained by reversing the order of elements using either numpy.flipud or numpy.fliplr. >>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.fliplr(a).diagonal()  # Horizontal flip
array([2, 4, 6])
>>> np.flipud(a).diagonal()  # Vertical flip
array([6, 4, 2])
 Note that the order in which the diagonal is retrieved varies depending on the flip function.


numpy.diff   numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)[source]

Calculate the n-th discrete difference along the given axis. The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively.  Parameters

aarray_like

Input array
nint, optional

The number of times values are differenced. If zero, the input is returned as-is.
axisint, optional

The axis along which the difference is taken, default is the last axis.
prepend, appendarray_like, optional

Values to prepend or append to a along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match a except along axis.  New in version 1.16.0.     Returns

diffndarray

The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. The type of the output is the same as the type of the difference between any two elements of a. This is the same as the type of a in most cases. A notable exception is datetime64, which results in a timedelta64 output array.      See also
gradient, ediff1d, cumsum

  Notes Type is preserved for boolean arrays, so the result will contain False when consecutive elements are the same and True when they differ. For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly: >>> u8_arr = np.array([1, 0], dtype=np.uint8)
>>> np.diff(u8_arr)
array([255], dtype=uint8)
>>> u8_arr[1,...] - u8_arr[0,...]
255
 If this is not desirable, then the array should be cast to a larger integer type first: >>> i16_arr = u8_arr.astype(np.int16)
>>> np.diff(i16_arr)
array([-1], dtype=int16)
 Examples >>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
array([ 1,  2,  3, -7])
>>> np.diff(x, n=2)
array([  1,   1, -10])
 >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
>>> np.diff(x)
array([[2, 3, 4],
       [5, 1, 2]])
>>> np.diff(x, axis=0)
array([[-1,  2,  0, -2]])
 >>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
>>> np.diff(x)
array([1, 1], dtype='timedelta64[D]')


numpy.digitize   numpy.digitize(x, bins, right=False)[source]

Return the indices of the bins to which each value in input array belongs.
right order of bins returned index i satisfies
False increasing bins[i-1] <= x < bins[i]
True increasing bins[i-1] < x <= bins[i]
False decreasing bins[i-1] > x >= bins[i]
True decreasing bins[i-1] >= x > bins[i]   If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate.  Parameters

xarray_like

Input array to be binned. Prior to NumPy 1.10.0, this array had to be 1-dimensional, but can now have any shape.
binsarray_like

Array of bins. It has to be 1-dimensional and monotonic.
rightbool, optional

Indicating whether the intervals include the right or the left bin edge. Default behavior is (right==False) indicating that the interval does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins.    Returns

indicesndarray of ints

Output array of indices, of same shape as x.    Raises
 ValueError

If bins is not monotonic.  TypeError

If the type of the input is complex.      See also
bincount, histogram, unique, searchsorted

  Notes If values in x are such that they fall outside the bin range, attempting to index bins with the indices that digitize returns will result in an IndexError.  New in version 1.10.0.  np.digitize is implemented in terms of np.searchsorted. This means that a binary search is used to bin the values, which scales much better for larger number of bins than the previous linear search. It also removes the requirement for the input array to be 1-dimensional. For monotonically _increasing_ bins, the following are equivalent: np.digitize(x, bins, right=True)
np.searchsorted(bins, x, side='left')
 Note that as the order of the arguments are reversed, the side must be too. The searchsorted call is marginally faster, as it does not do any monotonicity checks. Perhaps more importantly, it supports all dtypes. Examples >>> x = np.array([0.2, 6.4, 3.0, 1.6])
>>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
>>> inds = np.digitize(x, bins)
>>> inds
array([1, 4, 3, 2])
>>> for n in range(x.size):
...   print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]])
...
0.0 <= 0.2 < 1.0
4.0 <= 6.4 < 10.0
2.5 <= 3.0 < 4.0
1.0 <= 1.6 < 2.5
 >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
>>> bins = np.array([0, 5, 10, 15, 20])
>>> np.digitize(x,bins,right=True)
array([1, 2, 3, 4, 4])
>>> np.digitize(x,bins,right=False)
array([1, 3, 3, 4, 5])


numpy.disp   numpy.disp(mesg, device=None, linefeed=True)[source]

Display a message on a device.  Parameters

mesgstr

Message to display.
deviceobject

Device to write message. If None, defaults to sys.stdout which is very similar to print. device needs to have write() and flush() methods.
linefeedbool, optional

Option whether to print a line feed or not. Defaults to True.    Raises
 AttributeError

If device does not have a write() or flush() method.     Examples Besides sys.stdout, a file-like object can also be used as it has both required methods: >>> from io import StringIO
>>> buf = StringIO()
>>> np.disp(u'"Display" in a file', device=buf)
>>> buf.getvalue()
'"Display" in a file\n'


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


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


numpy.distutils.ccompiler_opt.CCompilerOpt   class numpy.distutils.ccompiler_opt.CCompilerOpt(ccompiler, cpu_baseline='min', cpu_dispatch='max', cache_path=None)[source]

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


numpy.distutils.core.Extension   class numpy.distutils.core.Extension(name, sources, include_dirs=None, define_macros=None, undef_macros=None, library_dirs=None, libraries=None, runtime_library_dirs=None, extra_objects=None, extra_compile_args=None, extra_link_args=None, export_symbols=None, swig_opts=None, depends=None, language=None, f2py_options=None, module_dirs=None, extra_c_compile_args=None, extra_cxx_compile_args=None, extra_f77_compile_args=None, extra_f90_compile_args=None)[source]

 Parameters

namestr

Extension name.
sourceslist of str

List of source file locations relative to the top directory of the package.
extra_compile_argslist of str

Extra command line arguments to pass to the compiler.
extra_f77_compile_argslist of str

Extra command line arguments to pass to the fortran77 compiler.
extra_f90_compile_argslist of str

Extra command line arguments to pass to the fortran90 compiler.     Methods
has_cxx_sources
has_f2py_sources


distutils.misc_util   numpy.distutils.misc_util.all_strings(lst)[source]

Return True if all items in lst are string objects.
   numpy.distutils.misc_util.allpath(name)[source]

Convert a /-separated pathname to one using the OS’s path separator.
   numpy.distutils.misc_util.appendpath(prefix, path)[source]

   numpy.distutils.misc_util.as_list(seq)[source]

   numpy.distutils.misc_util.blue_text(s)[source]

   numpy.distutils.misc_util.cyan_text(s)[source]

   numpy.distutils.misc_util.cyg2win32(path: str) → str[source]

Convert a path from Cygwin-native to Windows-native. Uses the cygpath utility (part of the Base install) to do the actual conversion. Falls back to returning the original path if this fails. Handles the default /cygdrive mount prefix as well as the /proc/cygdrive portable prefix, custom cygdrive prefixes such as / or /mnt, and absolute paths such as /usr/src/ or /home/username  Parameters

pathstr

The path to convert    Returns

converted_pathstr

The converted path     Notes Documentation for cygpath utility: https://cygwin.com/cygwin-ug-net/cygpath.html Documentation for the C function it wraps: https://cygwin.com/cygwin-api/func-cygwin-conv-path.html
   numpy.distutils.misc_util.default_config_dict(name=None, parent_name=None, local_path=None)[source]

Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py.
   numpy.distutils.misc_util.dict_append(d, **kws)[source]

   numpy.distutils.misc_util.dot_join(*args)[source]

   numpy.distutils.misc_util.exec_mod_from_location(modname, modfile)[source]

Use importlib machinery to import a module modname from the file modfile. Depending on the spec.loader, the module may not be registered in sys.modules.
   numpy.distutils.misc_util.filter_sources(sources)[source]

Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively.
   numpy.distutils.misc_util.generate_config_py(target)[source]

Generate config.py file containing system_info information used during building the package.  Usage:

config[‘py_modules’].append((packagename, ‘__config__’,generate_config_py))
   numpy.distutils.misc_util.get_build_architecture()[source]

   numpy.distutils.misc_util.get_cmd(cmdname, _cache={})[source]

   numpy.distutils.misc_util.get_data_files(data)[source]

   numpy.distutils.misc_util.get_dependencies(sources)[source]

   numpy.distutils.misc_util.get_ext_source_files(ext)[source]

   numpy.distutils.misc_util.get_frame(level=0)[source]

Return frame object from call stack with given level.
   numpy.distutils.misc_util.get_info(pkgname, dirs=None)[source]

Return an info dict for a given C library. The info dict contains the necessary options to use the C library.  Parameters

pkgnamestr

Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
dirssequence, optional

If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.    Returns

infodict

The dictionary with build information.    Raises
 PkgNotFound

If the package is not found.      See also
Configuration.add_npy_pkg_config, Configuration.add_installed_library

get_pkg_info
  Examples To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath')
>>> npymath_info
{'define_macros': [], 'libraries': ['npymath'], 'library_dirs':
['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}
 This info dict can then be used as input to a Configuration instance: config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)

   numpy.distutils.misc_util.get_language(sources)[source]

Determine language value (c,f77,f90) from sources
   numpy.distutils.misc_util.get_lib_source_files(lib)[source]

   numpy.distutils.misc_util.get_mathlibs(path=None)[source]

Return the MATHLIB line from numpyconfig.h
   numpy.distutils.misc_util.get_num_build_jobs()[source]

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

outint

number of parallel jobs that can be run
   numpy.distutils.misc_util.get_numpy_include_dirs()[source]

   numpy.distutils.misc_util.get_pkg_info(pkgname, dirs=None)[source]

Return library info for the given package.  Parameters

pkgnamestr

Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
dirssequence, optional

If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.    Returns

pkginfoclass instance

The LibraryInfo instance containing the build information.    Raises
 PkgNotFound

If the package is not found.      See also
Configuration.add_npy_pkg_config, Configuration.add_installed_library

get_info

   numpy.distutils.misc_util.get_script_files(scripts)[source]

   numpy.distutils.misc_util.gpaths(paths, local_path='', include_non_existing=True)[source]

Apply glob to paths and prepend local_path if needed.
   numpy.distutils.misc_util.green_text(s)[source]

   numpy.distutils.misc_util.has_cxx_sources(sources)[source]

Return True if sources contains C++ files
   numpy.distutils.misc_util.has_f_sources(sources)[source]

Return True if sources contains Fortran files
   numpy.distutils.misc_util.is_local_src_dir(directory)[source]

Return true if directory is local directory.
   numpy.distutils.misc_util.is_sequence(seq)[source]

   numpy.distutils.misc_util.is_string(s)[source]

   numpy.distutils.misc_util.mingw32()[source]

Return true when using mingw32 environment.
   numpy.distutils.misc_util.minrelpath(path)[source]

Resolve  and ‘.’ from path.
   numpy.distutils.misc_util.njoin(*path)[source]

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

   numpy.distutils.misc_util.sanitize_cxx_flags(cxxflags)[source]

Some flags are valid for C but not C++. Prune them.
   numpy.distutils.misc_util.terminal_has_colors()[source]

   numpy.distutils.misc_util.yellow_text(s)[source]


numpy.distutils.misc_util.allpath(name)[source]

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


numpy.distutils.misc_util.cyg2win32(path: str) → str[source]

Convert a path from Cygwin-native to Windows-native. Uses the cygpath utility (part of the Base install) to do the actual conversion. Falls back to returning the original path if this fails. Handles the default /cygdrive mount prefix as well as the /proc/cygdrive portable prefix, custom cygdrive prefixes such as / or /mnt, and absolute paths such as /usr/src/ or /home/username  Parameters

pathstr

The path to convert    Returns

converted_pathstr

The converted path     Notes Documentation for cygpath utility: https://cygwin.com/cygwin-ug-net/cygpath.html Documentation for the C function it wraps: https://cygwin.com/cygwin-api/func-cygwin-conv-path.html


numpy.distutils.misc_util.default_config_dict(name=None, parent_name=None, local_path=None)[source]

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


numpy.distutils.misc_util.exec_mod_from_location(modname, modfile)[source]

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


numpy.distutils.misc_util.filter_sources(sources)[source]

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


numpy.distutils.misc_util.generate_config_py(target)[source]

Generate config.py file containing system_info information used during building the package.  Usage:

config[‘py_modules’].append((packagename, ‘__config__’,generate_config_py))


numpy.distutils.misc_util.get_frame(level=0)[source]

Return frame object from call stack with given level.


numpy.distutils.misc_util.get_info(pkgname, dirs=None)[source]

Return an info dict for a given C library. The info dict contains the necessary options to use the C library.  Parameters

pkgnamestr

Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
dirssequence, optional

If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.    Returns

infodict

The dictionary with build information.    Raises
 PkgNotFound

If the package is not found.      See also
Configuration.add_npy_pkg_config, Configuration.add_installed_library

get_pkg_info
  Examples To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath')
>>> npymath_info
{'define_macros': [], 'libraries': ['npymath'], 'library_dirs':
['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}
 This info dict can then be used as input to a Configuration instance: config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)


numpy.distutils.misc_util.get_language(sources)[source]

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


numpy.distutils.misc_util.get_mathlibs(path=None)[source]

Return the MATHLIB line from numpyconfig.h


numpy.distutils.misc_util.get_num_build_jobs()[source]

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

outint

number of parallel jobs that can be run


numpy.distutils.misc_util.get_pkg_info(pkgname, dirs=None)[source]

Return library info for the given package.  Parameters

pkgnamestr

Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini).
dirssequence, optional

If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory.    Returns

pkginfoclass instance

The LibraryInfo instance containing the build information.    Raises
 PkgNotFound

If the package is not found.      See also
Configuration.add_npy_pkg_config, Configuration.add_installed_library

get_info


numpy.distutils.misc_util.gpaths(paths, local_path='', include_non_existing=True)[source]

Apply glob to paths and prepend local_path if needed.


numpy.distutils.misc_util.has_cxx_sources(sources)[source]

Return True if sources contains C++ files


numpy.distutils.misc_util.has_f_sources(sources)[source]

Return True if sources contains Fortran files


numpy.distutils.misc_util.is_local_src_dir(directory)[source]

Return true if directory is local directory.


numpy.distutils.misc_util.mingw32()[source]

Return true when using mingw32 environment.


numpy.distutils.misc_util.minrelpath(path)[source]

Resolve  and ‘.’ from path.


numpy.distutils.misc_util.njoin(*path)[source]

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


numpy.distutils.misc_util.sanitize_cxx_flags(cxxflags)[source]

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


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

Returns a true division of the inputs, element-wise. Unlike ‘floor division’, true division adjusts the output type to present the best answer, regardless of input types.  Parameters

x1array_like

Dividend array.
x2array_like

Divisor array. 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

This is a scalar if both x1 and x2 are scalars.     Notes In Python, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python. Examples >>> x = np.arange(5)
>>> np.true_divide(x, 4)
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ])
 >>> x/4
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ])
 >>> x//4
array([0, 0, 0, 0, 1])
 The / operator can be used as a shorthand for np.true_divide on ndarrays. >>> x = np.arange(5)
>>> x / 4
array([0.  , 0.25, 0.5 , 0.75, 1.  ])


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

Return element-wise quotient and remainder simultaneously.  New in version 1.13.0.  np.divmod(x, y) is equivalent to (x // y, x % y), but faster because it avoids redundant work. It is used to implement the Python built-in function divmod on NumPy arrays.  Parameters

x1array_like

Dividend array.
x2array_like

Divisor array. 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

out1ndarray

Element-wise quotient resulting from floor division. This is a scalar if both x1 and x2 are scalars.
out2ndarray

Element-wise remainder from floor division. This is a scalar if both x1 and x2 are scalars.      See also  floor_divide

Equivalent to Python’s // operator.  remainder

Equivalent to Python’s % operator.  modf

Equivalent to divmod(x, 1) for positive x with the return values switched.    Examples >>> np.divmod(np.arange(5), 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))
 The divmod function can be used as a shorthand for np.divmod on ndarrays. >>> x = np.arange(5)
>>> divmod(x, 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))


numpy.dot   numpy.dot(a, b, out=None)

Dot product of two arrays. Specifically,  If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred. If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
    Parameters

aarray_like

First argument.
barray_like

Second argument.
outndarray, optional

Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible.    Returns

outputndarray

Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.    Raises
 ValueError

If the last dimension of a is not the same size as the second-to-last dimension of b.      See also  vdot

Complex-conjugating dot product.  tensordot

Sum products over arbitrary axes.  einsum

Einstein summation convention.  matmul

‘@’ operator as method with out parameter.  linalg.multi_dot

Chained dot product.    Examples >>> np.dot(3, 4)
12
 Neither argument is complex-conjugated: >>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)
 For 2-D arrays it is the matrix product: >>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
       [2, 2]])
 >>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
>>> sum(a[2,3,2,:] * b[1,2,:,2])
499128


class numpy.double(x=0, /)[source]

Double-precision floating-point number type, compatible with Python float and C double.  Character code
'd'  Alias
numpy.float_  Alias on this platform (Linux x86_64)
numpy.float64: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.


numpy.dsplit   numpy.dsplit(ary, indices_or_sections)[source]

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

Split an array into multiple sub-arrays of equal size.    Examples >>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0.,   1.,   2.,   3.],
        [ 4.,   5.,   6.,   7.]],
       [[ 8.,   9.,  10.,  11.],
        [12.,  13.,  14.,  15.]]])
>>> np.dsplit(x, 2)
[array([[[ 0.,  1.],
        [ 4.,  5.]],
       [[ 8.,  9.],
        [12., 13.]]]), array([[[ 2.,  3.],
        [ 6.,  7.]],
       [[10., 11.],
        [14., 15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0.,   1.,   2.],
        [ 4.,   5.,   6.]],
       [[ 8.,   9.,  10.],
        [12.,  13.,  14.]]]),
 array([[[ 3.],
        [ 7.]],
       [[11.],
        [15.]]]),
array([], shape=(2, 2, 0), dtype=float64)]


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

Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1). Rebuilds arrays divided by dsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.  Parameters

tupsequence of arrays

The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.    Returns

stackedndarray

The array formed by stacking the given arrays, will be at least 3-D.      See also  concatenate

Join a sequence of arrays along an existing axis.  stack

Join a sequence of arrays along a new axis.  block

Assemble an nd-array from nested lists of blocks.  vstack

Stack arrays in sequence vertically (row wise).  hstack

Stack arrays in sequence horizontally (column wise).  column_stack

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

Split array along third axis.    Examples >>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
        [2, 3],
        [3, 4]]])
 >>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
       [[2, 3]],
       [[3, 4]]])


numpy.dtype   class numpy.dtype(dtype, align=False, copy=False)[source]

Create a data type object. A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types.  Parameters
 dtype

Object to be converted to a data type object.
alignbool, optional

Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be True only if obj is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flag isalignedstruct.
copybool, optional

Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object.      See also  result_type
  Examples Using array-scalar type: >>> np.dtype(np.int16)
dtype('int16')
 Structured type, one field name ‘f1’, containing int16: >>> np.dtype([('f1', np.int16)])
dtype([('f1', '<i2')])
 Structured type, one field named ‘f1’, in itself containing a structured type with one field: >>> np.dtype([('f1', [('f1', np.int16)])])
dtype([('f1', [('f1', '<i2')])])
 Structured type, two fields: the first field contains an unsigned int, the second an int32: >>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
dtype([('f1', '<u8'), ('f2', '<i4')])
 Using array-protocol type strings: >>> np.dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', 'S10')])
 Using comma-separated field formats. The shape is (2,3): >>> np.dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
 Using tuples. int is a fixed type, 3 the field’s shape. void is a flexible type, here of size 10: >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
dtype([('hello', '<i8', (3,)), ('world', 'V10')])
 Subdivide int16 into 2 int8’s, called x and y. 0 and 1 are the offsets in bytes: >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
 Using dictionaries. Two fields named ‘gender’ and ‘age’: >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
dtype([('gender', 'S1'), ('age', 'u1')])
 Offsets in bytes, here 0 and 25: >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
dtype([('surname', 'S25'), ('age', 'u1')])
  Attributes
 alignment

The required alignment (bytes) of this data-type according to the compiler.  base

Returns dtype for the base element of the subarrays, regardless of their dimension or shape.  byteorder

A character indicating the byte-order of this data-type object.  char

A unique character code for each of the 21 different built-in types.  descr

__array_interface__ description of the data-type.  fields

Dictionary of named fields defined for this data type, or None.  flags

Bit-flags describing how this data type is to be interpreted.  hasobject

Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes.  isalignedstruct

Boolean indicating whether the dtype is a struct which maintains field alignment.  isbuiltin

Integer indicating how this dtype relates to the built-in dtypes.  isnative

Boolean indicating whether the byte order of this dtype is native to the platform.  itemsize

The element size of this data-type object.  kind

A character code (one of ‘biufcmMOSUV’) identifying the general kind of data.  metadata

Either None or a readonly dictionary of metadata (mappingproxy).  name

A bit-width name for this data-type.  names

Ordered list of field names, or None if there are no fields.  ndim

Number of dimensions of the sub-array if this data type describes a sub-array, and 0 otherwise.  num

A unique number for each of the 21 different built-in types.  shape

Shape tuple of the sub-array if this data type describes a sub-array, and () otherwise.  str

The array-protocol typestring of this data-type object.  subdtype

Tuple (item_dtype, shape) if this dtype describes a sub-array, and None otherwise.  type
   Methods
newbyteorder([new_order]) Return a new dtype with a different byte order.


numpy.e

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