numpy.ediff1d   numpy.ediff1d(ary, to_end=None, to_begin=None)[source]

The differences between consecutive elements of an array.  Parameters

aryarray_like

If necessary, will be flattened before the differences are taken.
to_endarray_like, optional

Number(s) to append at the end of the returned differences.
to_beginarray_like, optional

Number(s) to prepend at the beginning of the returned differences.    Returns

ediff1dndarray

The differences. Loosely, this is ary.flat[1:] - ary.flat[:-1].      See also
diff, gradient

  Notes When applied to masked arrays, this function drops the mask information if the to_begin and/or to_end parameters are used. Examples >>> x = np.array([1, 2, 4, 7, 0])
>>> np.ediff1d(x)
array([ 1,  2,  3, -7])
 >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
array([-99,   1,   2, ...,  -7,  88,  99])
 The returned array is always 1D. >>> y = [[1, 2, 4], [1, 6, 24]]
>>> np.ediff1d(y)
array([ 1,  2, -3,  5, 18])


numpy.einsum   numpy.einsum(subscripts, *operands, out=None, dtype=None, order='K', casting='safe', optimize=False)[source]

Evaluates the Einstein summation convention on the operands. Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values. In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels. See the notes and examples for clarification.  Parameters

subscriptsstr

Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator ‘->’ is included as well as subscript labels of the precise output form.
operandslist of array_like

These are the arrays for the operation.
outndarray, optional

If provided, the calculation is done into this array.
dtype{data-type, None}, optional

If provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal casting parameter to allow the conversions. Default is None.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Controls the memory layout of the output. ‘C’ means it should be C contiguous. ‘F’ means it should be Fortran contiguous, ‘A’ means it should be ‘F’ if the inputs are all ‘F’, ‘C’ otherwise. ‘K’ means it should be as close to the layout as the inputs as is possible, including arbitrarily permuted axes. Default is ‘K’.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Controls what kind of data casting may occur. Setting this to ‘unsafe’ is not recommended, as it can adversely affect accumulations.  ‘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.  Default is ‘safe’.
optimize{False, True, ‘greedy’, ‘optimal’}, optional

Controls if intermediate optimization should occur. No optimization will occur if False and True will default to the ‘greedy’ algorithm. Also accepts an explicit contraction list from the np.einsum_path function. See np.einsum_path for more details. Defaults to False.    Returns

outputndarray

The calculation based on the Einstein summation convention.      See also
einsum_path, dot, inner, outer, tensordot, linalg.multi_dot

einops

similar verbose interface is provided by einops package to cover additional operations: transpose, reshape/flatten, repeat/tile, squeeze/unsqueeze and reductions.  opt_einsum

opt_einsum optimizes contraction order for einsum-like expressions in backend-agnostic manner.    Notes  New in version 1.6.0.  The Einstein summation convention can be used to compute many multi-dimensional, linear algebraic array operations. einsum provides a succinct way of representing these. A non-exhaustive list of these operations, which can be computed by einsum, is shown below along with examples:  Trace of an array, numpy.trace. Return a diagonal, numpy.diag. Array axis summations, numpy.sum. Transpositions and permutations, numpy.transpose. Matrix multiplication and dot product, numpy.matmul numpy.dot. Vector inner and outer products, numpy.inner numpy.outer. Broadcasting, element-wise and scalar multiplication, numpy.multiply. Tensor contractions, numpy.tensordot. Chained array operations, in efficient calculation order, numpy.einsum_path.  The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Whenever a label is repeated it is summed, so np.einsum('i,i', a, b) is equivalent to np.inner(a,b). If a label appears only once, it is not summed, so np.einsum('i', a) produces a view of a with no changes. A further example np.einsum('ij,jk', a, b) describes traditional matrix multiplication and is equivalent to np.matmul(a,b). Repeated subscript labels in one operand take the diagonal. For example, np.einsum('ii', a) is equivalent to np.trace(a). In implicit mode, the chosen subscripts are important since the axes of the output are reordered alphabetically. This means that np.einsum('ij', a) doesn’t affect a 2D array, while np.einsum('ji', a) takes its transpose. Additionally, np.einsum('ij,jk', a, b) returns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transpose of the multiplication since subscript ‘h’ precedes subscript ‘i’. In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier ‘->’ as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like np.sum(a, axis=-1), and np.einsum('ii->i', a) is like np.diag(a). The difference is that einsum does not allow broadcasting by default. Additionally np.einsum('ij,jh->ih', a, b) directly specifies the order of the output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode. To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b). When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as np.einsum('ii->i', a) produces a view (changed in version 1.10.0). einsum also provides an alternative way to provide the subscripts and operands as einsum(op0, sublist0, op1, sublist1, ..., [sublistout]). If the output shape is not provided in this format einsum will be calculated in implicit mode, otherwise it will be performed explicitly. The examples below have corresponding einsum calls with the two parameter methods.  New in version 1.10.0.  Views returned from einsum are now writeable whenever the input array is writeable. For example, np.einsum('ijk...->kji...', a) will now have the same effect as np.swapaxes(a, 0, 2) and np.einsum('ii->i', a) will return a writeable view of the diagonal of a 2D array.  New in version 1.12.0.  Added the optimize argument which will optimize the contraction order of an einsum expression. For a contraction with three or more operands this can greatly increase the computational efficiency at the cost of a larger memory footprint during computation. Typically a ‘greedy’ algorithm is applied which empirical tests have shown returns the optimal path in the majority of cases. In some cases ‘optimal’ will return the superlative path through a more expensive, exhaustive search. For iterative calculations it may be advisable to calculate the optimal path once and reuse that path by supplying it as an argument. An example is given below. See numpy.einsum_path for more details. Examples >>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)
 Trace of a matrix: >>> np.einsum('ii', a)
60
>>> np.einsum(a, [0,0])
60
>>> np.trace(a)
60
 Extract the diagonal (requires explicit form): >>> np.einsum('ii->i', a)
array([ 0,  6, 12, 18, 24])
>>> np.einsum(a, [0,0], [0])
array([ 0,  6, 12, 18, 24])
>>> np.diag(a)
array([ 0,  6, 12, 18, 24])
 Sum over an axis (requires explicit form): >>> np.einsum('ij->i', a)
array([ 10,  35,  60,  85, 110])
>>> np.einsum(a, [0,1], [0])
array([ 10,  35,  60,  85, 110])
>>> np.sum(a, axis=1)
array([ 10,  35,  60,  85, 110])
 For higher dimensional arrays summing a single axis can be done with ellipsis: >>> np.einsum('...j->...', a)
array([ 10,  35,  60,  85, 110])
>>> np.einsum(a, [Ellipsis,1], [Ellipsis])
array([ 10,  35,  60,  85, 110])
 Compute a matrix transpose, or reorder any number of axes: >>> np.einsum('ji', c)
array([[0, 3],
       [1, 4],
       [2, 5]])
>>> np.einsum('ij->ji', c)
array([[0, 3],
       [1, 4],
       [2, 5]])
>>> np.einsum(c, [1,0])
array([[0, 3],
       [1, 4],
       [2, 5]])
>>> np.transpose(c)
array([[0, 3],
       [1, 4],
       [2, 5]])
 Vector inner products: >>> np.einsum('i,i', b, b)
30
>>> np.einsum(b, [0], b, [0])
30
>>> np.inner(b,b)
30
 Matrix vector multiplication: >>> np.einsum('ij,j', a, b)
array([ 30,  80, 130, 180, 230])
>>> np.einsum(a, [0,1], b, [1])
array([ 30,  80, 130, 180, 230])
>>> np.dot(a, b)
array([ 30,  80, 130, 180, 230])
>>> np.einsum('...j,j', a, b)
array([ 30,  80, 130, 180, 230])
 Broadcasting and scalar multiplication: >>> np.einsum('..., ...', 3, c)
array([[ 0,  3,  6],
       [ 9, 12, 15]])
>>> np.einsum(',ij', 3, c)
array([[ 0,  3,  6],
       [ 9, 12, 15]])
>>> np.einsum(3, [Ellipsis], c, [Ellipsis])
array([[ 0,  3,  6],
       [ 9, 12, 15]])
>>> np.multiply(3, c)
array([[ 0,  3,  6],
       [ 9, 12, 15]])
 Vector outer product: >>> np.einsum('i,j', np.arange(2)+1, b)
array([[0, 1, 2, 3, 4],
       [0, 2, 4, 6, 8]])
>>> np.einsum(np.arange(2)+1, [0], b, [1])
array([[0, 1, 2, 3, 4],
       [0, 2, 4, 6, 8]])
>>> np.outer(np.arange(2)+1, b)
array([[0, 1, 2, 3, 4],
       [0, 2, 4, 6, 8]])
 Tensor contraction: >>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])
>>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])
>>> np.tensordot(a,b, axes=([1,0],[0,1]))
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])
 Writeable returned arrays (since version 1.10.0): >>> a = np.zeros((3, 3))
>>> np.einsum('ii->i', a)[:] = 1
>>> a
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
 Example of ellipsis use: >>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('k...,jk', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
 Chained array operations. For more complicated contractions, speed ups might be achieved by repeatedly computing a ‘greedy’ path or pre-computing the ‘optimal’ path and repeatedly applying it, using an einsum_path insertion (since version 1.12.0). Performance improvements can be particularly significant with larger arrays: >>> a = np.ones(64).reshape(2,4,8)
 Basic einsum: ~1520ms (benchmarked on 3.1GHz Intel i5.) >>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
 Sub-optimal einsum (due to repeated path calculation time): ~330ms >>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')
 Greedy einsum (faster optimal path approximation): ~160ms >>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
 Optimal einsum (best usage pattern in some use cases): ~110ms >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')[0]
>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)


numpy.einsum_path   numpy.einsum_path(subscripts, *operands, optimize='greedy')[source]

Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays.  Parameters

subscriptsstr

Specifies the subscripts for summation.
*operandslist of array_like

These are the arrays for the operation.
optimize{bool, list, tuple, ‘greedy’, ‘optimal’}

Choose the type of path. If a tuple is provided, the second argument is assumed to be the maximum intermediate size created. If only a single argument is provided the largest input or output array size is used as a maximum intermediate size.  if a list is given that starts with einsum_path, uses this as the contraction path if False no optimization is taken if True defaults to the ‘greedy’ algorithm ‘optimal’ An algorithm that combinatorially explores all possible ways of contracting the listed tensors and choosest the least costly path. Scales exponentially with the number of terms in the contraction. ‘greedy’ An algorithm that chooses the best pair contraction at each step. Effectively, this algorithm searches the largest inner, Hadamard, and then outer products at each step. Scales cubically with the number of terms in the contraction. Equivalent to the ‘optimal’ path for most contractions.  Default is ‘greedy’.    Returns

pathlist of tuples

A list representation of the einsum path.
string_reprstr

A printable representation of the einsum path.      See also
einsum, linalg.multi_dot

  Notes The resulting path indicates which terms of the input contraction should be contracted first, the result of this contraction is then appended to the end of the contraction list. This list can then be iterated over until all intermediate contractions are complete. Examples We can begin with a chain dot example. In this case, it is optimal to contract the b and c tensors first as represented by the first element of the path (1, 2). The resulting tensor is added to the end of the contraction and the remaining contraction (0, 1) is then completed. >>> np.random.seed(123)
>>> a = np.random.rand(2, 2)
>>> b = np.random.rand(2, 5)
>>> c = np.random.rand(5, 2)
>>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
>>> print(path_info[0])
['einsum_path', (1, 2), (0, 1)]
>>> print(path_info[1])
  Complete contraction:  ij,jk,kl->il # may vary
         Naive scaling:  4
     Optimized scaling:  3
      Naive FLOP count:  1.600e+02
  Optimized FLOP count:  5.600e+01
   Theoretical speedup:  2.857
  Largest intermediate:  4.000e+00 elements
-------------------------------------------------------------------------
scaling                  current                                remaining
-------------------------------------------------------------------------
   3                   kl,jk->jl                                ij,jl->il
   3                   jl,ij->il                                   il->il
 A more complex index transformation example. >>> I = np.random.rand(10, 10, 10, 10)
>>> C = np.random.rand(10, 10)
>>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
...                            optimize='greedy')
 >>> print(path_info[0])
['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
>>> print(path_info[1])
  Complete contraction:  ea,fb,abcd,gc,hd->efgh # may vary
         Naive scaling:  8
     Optimized scaling:  5
      Naive FLOP count:  8.000e+08
  Optimized FLOP count:  8.000e+05
   Theoretical speedup:  1000.000
  Largest intermediate:  1.000e+04 elements
--------------------------------------------------------------------------
scaling                  current                                remaining
--------------------------------------------------------------------------
   5               abcd,ea->bcde                      fb,gc,hd,bcde->efgh
   5               bcde,fb->cdef                         gc,hd,cdef->efgh
   5               cdef,gc->defg                            hd,defg->efgh
   5               defg,hd->efgh                               efgh->efgh


numpy.empty   numpy.empty(shape, dtype=float, order='C', *, like=None)

Return a new array of given shape and type, without initializing entries.  Parameters

shapeint or tuple of int

Shape of the empty array, e.g., (2, 3) or 2.
dtypedata-type, optional

Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64.
order{‘C’, ‘F’}, optional, default: ‘C’

Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

outndarray

Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.      See also  empty_like

Return an empty array with shape and type of input.  ones

Return a new array setting values to one.  zeros

Return a new array setting values to zero.  full

Return a new array of given shape filled with value.    Notes empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution. Examples >>> np.empty([2, 2])
array([[ -9.74499359e+001,   6.69583040e-309],
       [  2.13182611e-314,   3.06959433e-309]])         #uninitialized
 >>> np.empty([2, 2], dtype=int)
array([[-1073741821, -1067949133],
       [  496041986,    19249760]])                     #uninitialized


numpy.empty_like   numpy.empty_like(prototype, dtype=None, order='K', subok=True, shape=None)

Return a new array with the same shape and type as a given array.  Parameters

prototypearray_like

The shape and data-type of prototype define these same attributes of the returned array.
dtypedata-type, optional

Overrides the data type of the result.  New in version 1.6.0.
order{‘C’, ‘F’, ‘A’, or ‘K’}, optional

Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if prototype is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of prototype as closely as possible.  New in version 1.6.0.
subokbool, optional.

If True, then the newly created array will use the sub-class type of prototype, otherwise it will be a base-class array. Defaults to True.
shapeint or sequence of ints, optional.

Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.  New in version 1.17.0.     Returns

outndarray

Array of uninitialized (arbitrary) data with the same shape and type as prototype.      See also  ones_like

Return an array of ones with shape and type of input.  zeros_like

Return an array of zeros with shape and type of input.  full_like

Return a new array with shape of input filled with value.  empty

Return a new uninitialized array.    Notes This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be marginally faster than the functions that do set the array values. Examples >>> a = ([1,2,3], [4,5,6])                         # a is array-like
>>> np.empty_like(a)
array([[-1073741821, -1073741821,           3],    # uninitialized
       [          0,           0, -1073741821]])
>>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> np.empty_like(a)
array([[ -2.00000715e+000,   1.48219694e-323,  -2.00000572e+000], # uninitialized
       [  4.38791518e-305,  -2.00000715e+000,   4.17269252e-309]])


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

Return (x1 == x2) element-wise.  Parameters

x1, x2array_like

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

Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.      See also
not_equal, greater_equal, less_equal, greater, less

  Examples >>> np.equal([0, 1, 3], np.arange(3))
array([ True,  True, False])
 What is compared are values, not types. So an int (1) and an array of length one can evaluate as True: >>> np.equal(1, np.ones(1))
array([ True])
 The == operator can be used as a shorthand for np.equal on ndarrays. >>> a = np.array([2, 4, 6])
>>> b = np.array([2, 4, 2])
>>> a == b
array([ True,  True, False])


numpy.errstate   class numpy.errstate(**kwargs)[source]

Context manager for floating-point error handling. Using an instance of errstate as a context manager allows statements in that context to execute with a known error handling behavior. Upon entering the context the error handling is set with seterr and seterrcall, and upon exiting it is reset to what it was before.  Changed in version 1.17.0: errstate is also usable as a function decorator, saving a level of indentation if an entire function is wrapped. See contextlib.ContextDecorator for more information.   Parameters

kwargs{divide, over, under, invalid}

Keyword arguments. The valid keywords are the possible floating-point exceptions. Each keyword should have a string value that defines the treatment for the particular error. Possible values are {‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}.      See also
seterr, geterr, seterrcall, geterrcall

  Notes For complete documentation of the types of floating-point exceptions and treatment options, see seterr. Examples >>> olderr = np.seterr(all='ignore')  # Set error handling to known state.
 >>> np.arange(3) / 0.
array([nan, inf, inf])
>>> with np.errstate(divide='warn'):
...     np.arange(3) / 0.
array([nan, inf, inf])
 >>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
...     np.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt
 Outside the context the error handling behavior has not changed: >>> np.geterr()
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
 Methods
__call__(func) Call self as a function.


numpy.euler_gamma

γ = 0.5772156649015328606065120900824024310421... References https://en.wikipedia.org/wiki/Euler-Mascheroni_constant


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

Calculate the exponential of all elements in the input array.  Parameters

xarray_like

Input values.
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, element-wise exponential of x. This is a scalar if x is a scalar.      See also  expm1

Calculate exp(x) - 1 for all elements in the array.  exp2

Calculate 2**x for all elements in the array.    Notes The irrational number e is also known as Euler’s number. It is approximately 2.718281, and is the base of the natural logarithm, ln (this means that, if \(x = \ln y = \log_e y\), then \(e^x = y\). For real input, exp(x) is always positive. For complex arguments, x = a + ib, we can write \(e^x = e^a e^{ib}\). The first term, \(e^a\), is already known (it is the real argument, described above). The second term, \(e^{ib}\), is \(\cos b + i \sin b\), a function with magnitude 1 and a periodic phase. References  1
Wikipedia, “Exponential function”, https://en.wikipedia.org/wiki/Exponential_function  2
M. Abramovitz and I. A. Stegun, “Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables,” Dover, 1964, p. 69, https://personal.math.ubc.ca/~cbm/aands/page_69.htm   Examples Plot the magnitude and phase of exp(x) in the complex plane: >>> import matplotlib.pyplot as plt
 >>> x = np.linspace(-2*np.pi, 2*np.pi, 100)
>>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane
>>> out = np.exp(xx)
 >>> plt.subplot(121)
>>> plt.imshow(np.abs(out),
...            extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='gray')
>>> plt.title('Magnitude of exp(x)')
 >>> plt.subplot(122)
>>> plt.imshow(np.angle(out),
...            extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='hsv')
>>> plt.title('Phase (angle) of exp(x)')
>>> plt.show()


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

Calculate 2**p for all p in the input array.  Parameters

xarray_like

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

Element-wise 2 to the power x. This is a scalar if x is a scalar.      See also  power
  Notes  New in version 1.3.0.  Examples >>> np.exp2([2, 3])
array([ 4.,  8.])


numpy.expand_dims   numpy.expand_dims(a, axis)[source]

Expand the shape of an array. Insert a new axis that will appear at the axis position in the expanded array shape.  Parameters

aarray_like

Input array.
axisint or tuple of ints

Position in the expanded axes where the new axis (or axes) is placed.  Deprecated since version 1.13.0: Passing an axis where axis > a.ndim will be treated as axis == a.ndim, and passing axis < -a.ndim - 1 will be treated as axis == 0. This behavior is deprecated.   Changed in version 1.18.0: A tuple of axes is now supported. Out of range axes as described above are now forbidden and raise an AxisError.     Returns

resultndarray

View of a with the number of dimensions increased.      See also  squeeze

The inverse operation, removing singleton dimensions  reshape

Insert, remove, and combine dimensions, and resize existing ones
doc.indexing, atleast_1d, atleast_2d, atleast_3d

  Examples >>> x = np.array([1, 2])
>>> x.shape
(2,)
 The following is equivalent to x[np.newaxis, :] or x[np.newaxis]: >>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
 The following is equivalent to x[:, np.newaxis]: >>> y = np.expand_dims(x, axis=1)
>>> y
array([[1],
       [2]])
>>> y.shape
(2, 1)
 axis may also be a tuple: >>> y = np.expand_dims(x, axis=(0, 1))
>>> y
array([[[1, 2]]])
 >>> y = np.expand_dims(x, axis=(2, 0))
>>> y
array([[[1],
        [2]]])
 Note that some examples may use None instead of np.newaxis. These are the same objects: >>> np.newaxis is None
True


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

Calculate exp(x) - 1 for all elements in the array.  Parameters

xarray_like

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

Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.      See also  log1p

log(1 + x), the inverse of expm1.    Notes This function provides greater precision than exp(x) - 1 for small values of x. Examples The true value of exp(1e-10) - 1 is 1.00000000005e-10 to about 32 significant digits. This example shows the superiority of expm1 in this case. >>> np.expm1(1e-10)
1.00000000005e-10
>>> np.exp(1e-10) - 1
1.000000082740371e-10


numpy.extract   numpy.extract(condition, arr)[source]

Return the elements of an array that satisfy some condition. This is equivalent to np.compress(ravel(condition), ravel(arr)). If condition is boolean np.extract is equivalent to arr[condition]. Note that place does the exact opposite of extract.  Parameters

conditionarray_like

An array whose nonzero or True entries indicate the elements of arr to extract.
arrarray_like

Input array of the same size as condition.    Returns

extractndarray

Rank 1 array of values from arr where condition is True.      See also
take, put, copyto, compress, place

  Examples >>> arr = np.arange(12).reshape((3, 4))
>>> arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> condition = np.mod(arr, 3)==0
>>> condition
array([[ True, False, False,  True],
       [False, False,  True, False],
       [False,  True, False, False]])
>>> np.extract(condition, arr)
array([0, 3, 6, 9])
 If condition is boolean: >>> arr[condition]
array([0, 3, 6, 9])


numpy.eye   numpy.eye(N, M=None, k=0, dtype=<class 'float'>, order='C', *, like=None)[source]

Return a 2-D array with ones on the diagonal and zeros elsewhere.  Parameters

Nint

Number of rows in the output.
Mint, optional

Number of columns in the output. If None, defaults to N.
kint, optional

Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
dtypedata-type, optional

Data-type of the returned array.
order{‘C’, ‘F’}, optional

Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory.  New in version 1.14.0.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

Indarray of shape (N,M)

An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.      See also  identity

(almost) equivalent function  diag

diagonal 2-D array from a 1-D array specified by the user.    Examples >>> np.eye(2, dtype=int)
array([[1, 0],
       [0, 1]])
>>> np.eye(3, k=1)
array([[0.,  1.,  0.],
       [0.,  0.,  1.],
       [0.,  0.,  0.]])


numpy.f2py.get_include()[source]

Return the directory that contains the fortranobject.c and .h files.  Note This function is not needed when building an extension with numpy.distutils directly from .f and/or .pyf files in one go.  Python extension modules built with f2py-generated code need to use fortranobject.c as a source file, and include the fortranobject.h header. This function can be used to obtain the directory containing both of these files.  Returns

include_pathstr

Absolute path to the directory containing fortranobject.c and fortranobject.h.      See also  numpy.get_include

function that returns the numpy include directory    Notes  New in version 1.22.0.  Unless the build system you are using has specific support for f2py, building a Python extension using a .pyf signature file is a two-step process. For a module mymod:  Step 1: run python -m numpy.f2py mymod.pyf --quiet. This generates _mymodmodule.c and (if needed) _fblas-f2pywrappers.f files next to mymod.pyf.
Step 2: build your Python extension module. This requires the following source files:  _mymodmodule.c
_mymod-f2pywrappers.f (if it was generated in step 1) fortranobject.c


numpy.f2py.run_main(comline_list)[source]

Equivalent to running: f2py <args>
 where <args>=string.join(<list>,' '), but in Python. Unless -h is used, this function returns a dictionary containing information on generated modules and their dependencies on source files. For example, the command f2py -m scalar scalar.f can be executed from Python as follows You cannot build extension modules with this function, that is, using -c is not allowed. Use compile command instead Examples >>> import numpy.f2py
>>> r = numpy.f2py.run_main(['-m','scalar','doc/source/f2py/scalar.f'])
Reading fortran codes...
        Reading file 'doc/source/f2py/scalar.f' (format:fix,strict)
Post-processing...
        Block: scalar
                        Block: FOO
Building modules...
        Building module "scalar"...
        Wrote C/API module "scalar" to file "./scalarmodule.c"
>>> print(r)
{'scalar': {'h': ['/home/users/pearu/src_cvs/f2py/src/fortranobject.h'],
	 'csrc': ['./scalarmodule.c',
                  '/home/users/pearu/src_cvs/f2py/src/fortranobject.c']}}


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

Compute the absolute values element-wise. This function returns the absolute values (positive magnitude) of the data in x. Complex values are not handled, use absolute to find the absolute values of complex data.  Parameters

xarray_like

The array of numbers for which the absolute values are required. If x is a scalar, the result y will also be a scalar.
outndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

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

yndarray or scalar

The absolute values of x, the returned values are always floats. This is a scalar if x is a scalar.      See also  absolute

Absolute values including complex types.    Examples >>> np.fabs(-1)
1.0
>>> np.fabs([-1.2, 1.2])
array([ 1.2,  1.2])


numpy.fill_diagonal   numpy.fill_diagonal(a, val, wrap=False)[source]

Fill the main diagonal of the given array of any dimensionality. For an array a with a.ndim >= 2, the diagonal is the list of locations with indices a[i, ..., i] all identical. This function modifies the input array in-place, it does not return a value.  Parameters

aarray, at least 2-D.

Array whose diagonal is to be filled, it gets modified in-place.
valscalar or array_like

Value(s) to write on the diagonal. If val is scalar, the value is written along the diagonal. If array-like, the flattened val is written along the diagonal, repeating if necessary to fill all diagonal entries.
wrapbool

For tall matrices in NumPy version up to 1.6.2, the diagonal “wrapped” after N columns. You can have this behavior with this option. This affects only tall matrices.      See also
diag_indices, diag_indices_from

  Notes  New in version 1.4.0.  This functionality can be obtained via diag_indices, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples >>> a = np.zeros((3, 3), int)
>>> np.fill_diagonal(a, 5)
>>> a
array([[5, 0, 0],
       [0, 5, 0],
       [0, 0, 5]])
 The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int)
>>> np.fill_diagonal(a, 4)
 We only show a few blocks for clarity: >>> a[0, 0]
array([[4, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
>>> a[1, 1]
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 0]])
>>> a[2, 2]
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 4]])
 The wrap option affects only tall matrices: >>> # tall matrices no wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4)
>>> a
array([[4, 0, 0],
       [0, 4, 0],
       [0, 0, 4],
       [0, 0, 0],
       [0, 0, 0]])
 >>> # tall matrices wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0],
       [0, 4, 0],
       [0, 0, 4],
       [0, 0, 0],
       [4, 0, 0]])
 >>> # wide matrices
>>> a = np.zeros((3, 5), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0, 0, 0],
       [0, 4, 0, 0, 0],
       [0, 0, 4, 0, 0]])
 The anti-diagonal can be filled by reversing the order of elements using either numpy.flipud or numpy.fliplr. >>> a = np.zeros((3, 3), int);
>>> np.fill_diagonal(np.fliplr(a), [1,2,3])  # Horizontal flip
>>> a
array([[0, 0, 1],
       [0, 2, 0],
       [3, 0, 0]])
>>> np.fill_diagonal(np.flipud(a), [1,2,3])  # Vertical flip
>>> a
array([[0, 0, 3],
       [0, 2, 0],
       [1, 0, 0]])
 Note that the order in which the diagonal is filled varies depending on the flip function.


numpy.find_common_type   numpy.find_common_type(array_types, scalar_types)[source]

Determine common type following standard coercion rules.  Parameters

array_typessequence

A list of dtypes or dtype convertible objects representing arrays.
scalar_typessequence

A list of dtypes or dtype convertible objects representing scalars.    Returns

datatypedtype

The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.      See also
dtype, common_type, can_cast, mintypecode

  Examples >>> np.find_common_type([], [np.int64, np.float32, complex])
dtype('complex128')
>>> np.find_common_type([np.int64, np.float32], [])
dtype('float64')
 The standard casting rules ensure that a scalar cannot up-cast an array unless the scalar is of a fundamentally different kind of data (i.e. under a different hierarchy in the data type hierarchy) then the array: >>> np.find_common_type([np.float32], [np.int64, np.float64])
dtype('float32')
 Complex is of a different type, so it up-casts the float in the array_types argument: >>> np.find_common_type([np.float32], [complex])
dtype('complex128')
 Type specifier strings are convertible to dtypes and can therefore be used instead of dtypes: >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])
dtype('complex128')


numpy.finfo   class numpy.finfo(dtype)[source]

Machine limits for floating point types.  Parameters

dtypefloat, dtype, or instance

Kind of floating point data-type about which to get information.      See also  MachAr

The implementation of the tests that produce this information.  iinfo

The equivalent for integer data types.  spacing

The distance between a value and the nearest adjacent number  nextafter

The next floating point value after x1 towards x2    Notes For developers of NumPy: do not instantiate this at the module level. The initial calculation of these parameters is expensive and negatively impacts import times. These objects are cached, so calling finfo() repeatedly inside your functions is not a problem. Note that smallest_normal is not actually the smallest positive representable value in a NumPy floating point type. As in the IEEE-754 standard [1], NumPy floating point types make use of subnormal numbers to fill the gap between 0 and smallest_normal. However, subnormal numbers may have significantly reduced precision [2]. References  1
IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008, pp.1-70, 2008, http://www.doi.org/10.1109/IEEESTD.2008.4610935  2
Wikipedia, “Denormal Numbers”, https://en.wikipedia.org/wiki/Denormal_number    Attributes

bitsint

The number of bits occupied by the type.
epsfloat

The difference between 1.0 and the next smallest representable float larger than 1.0. For example, for 64-bit binary floats in the IEEE-754 standard, eps = 2**-52, approximately 2.22e-16.
epsnegfloat

The difference between 1.0 and the next smallest representable float less than 1.0. For example, for 64-bit binary floats in the IEEE-754 standard, epsneg = 2**-53, approximately 1.11e-16.
iexpint

The number of bits in the exponent portion of the floating point representation.
macharMachAr

The object which calculated these parameters and holds more detailed information.
machepint

The exponent that yields eps.
maxfloating point number of the appropriate type

The largest representable number.
maxexpint

The smallest positive power of the base (2) that causes overflow.
minfloating point number of the appropriate type

The smallest representable number, typically -max.
minexpint

The most negative power of the base (2) consistent with there being no leading 0’s in the mantissa.
negepint

The exponent that yields epsneg.
nexpint

The number of bits in the exponent including its sign and bias.
nmantint

The number of bits in the mantissa.
precisionint

The approximate number of decimal digits to which this kind of float is precise.
resolutionfloating point number of the appropriate type

The approximate decimal resolution of this type, i.e., 10**-precision.
tinyfloat

Return the value for tiny, alias of smallest_normal.
smallest_normalfloat

Return the value for the smallest normal.
smallest_subnormalfloat

The smallest positive floating point number with 0 as leading bit in the mantissa following IEEE-754.


numpy.fix   numpy.fix(x, out=None)[source]

Round to nearest integer towards zero. Round an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.  Parameters

xarray_like

An array of floats to be rounded
outndarray, optional

A location into which the result is stored. If provided, it must have a shape that the input broadcasts to. If not provided or None, a freshly-allocated array is returned.    Returns

outndarray of floats

A float array with the same dimensions as the input. If second argument is not supplied then a float array is returned with the rounded values. If a second argument is supplied the result is stored there. The return value out is then a reference to that array.      See also
rint, trunc, floor, ceil

around

Round to given number of decimals    Examples >>> np.fix(3.14)
3.0
>>> np.fix(3)
3.0
>>> np.fix([2.1, 2.9, -2.1, -2.9])
array([ 2.,  2., -2., -2.])


numpy.flatiter   class numpy.flatiter[source]

Flat iterator object to iterate over arrays. A flatiter iterator is returned by x.flat for any array x. It allows iterating over the array as if it were a 1-D array, either in a for-loop or by calling its next method. Iteration is done in row-major, C-style order (the last index varying the fastest). The iterator can also be indexed using basic slicing or advanced indexing.  See also  ndarray.flat

Return a flat iterator over an array.  ndarray.flatten

Returns a flattened copy of an array.    Notes A flatiter iterator can not be constructed directly from Python code by calling the flatiter constructor. Examples >>> x = np.arange(6).reshape(2, 3)
>>> fl = x.flat
>>> type(fl)
<class 'numpy.flatiter'>
>>> for item in fl:
...     print(item)
...
0
1
2
3
4
5
 >>> fl[2:4]
array([2, 3])
  Attributes
 base

A reference to the array that is iterated over.  coords

An N-dimensional tuple of current coordinates.  index

Current flat index into the array.     Methods
copy() Get a copy of the iterator as a 1-D array.


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

Return indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0].  Parameters

aarray_like

Input data.    Returns

resndarray

Output array, containing the indices of the elements of a.ravel() that are non-zero.      See also  nonzero

Return the indices of the non-zero elements of the input array.  ravel

Return a 1-D array containing the elements of the input array.    Examples >>> x = np.arange(-2, 3)
>>> x
array([-2, -1,  0,  1,  2])
>>> np.flatnonzero(x)
array([0, 1, 3, 4])
 Use the indices of the non-zero elements as an index array to extract these elements: >>> x.ravel()[np.flatnonzero(x)]
array([-2, -1,  1,  2])


class numpy.flexible[source]

Abstract base class of all scalar types without predefined length. The actual size of these types depends on the specific np.dtype instantiation.


numpy.flip   numpy.flip(m, axis=None)[source]

Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.  New in version 1.12.0.   Parameters

marray_like

Input array.
axisNone or int or tuple of ints, optional

Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple.  Changed in version 1.15.0: None and tuples of axes are supported     Returns

outarray_like

A view of m with the entries of axis reversed. Since a view is returned, this operation is done in constant time.      See also  flipud

Flip an array vertically (axis=0).  fliplr

Flip an array horizontally (axis=1).    Notes flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m). flip(m, n) corresponds to m[...,::-1,...] with ::-1 at position n. flip(m) corresponds to m[::-1,::-1,...,::-1] with ::-1 at all positions. flip(m, (0, 1)) corresponds to m[::-1,::-1,...] with ::-1 at position 0 and position 1. Examples >>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> np.flip(A, 0)
array([[[4, 5],
        [6, 7]],
       [[0, 1],
        [2, 3]]])
>>> np.flip(A, 1)
array([[[2, 3],
        [0, 1]],
       [[6, 7],
        [4, 5]]])
>>> np.flip(A)
array([[[7, 6],
        [5, 4]],
       [[3, 2],
        [1, 0]]])
>>> np.flip(A, (0, 2))
array([[[5, 4],
        [7, 6]],
       [[1, 0],
        [3, 2]]])
>>> A = np.random.randn(3,4,5)
>>> np.all(np.flip(A,2) == A[:,:,::-1,...])
True


numpy.fliplr   numpy.fliplr(m)[source]

Reverse the order of elements along axis 1 (left/right). For a 2-D array, this flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.  Parameters

marray_like

Input array, must be at least 2-D.    Returns

fndarray

A view of m with the columns reversed. Since a view is returned, this operation is \(\mathcal O(1)\).      See also  flipud

Flip array in the up/down direction.  flip

Flip array in one or more dimensions.  rot90

Rotate array counterclockwise.    Notes Equivalent to m[:,::-1] or np.flip(m, axis=1). Requires the array to be at least 2-D. Examples >>> A = np.diag([1.,2.,3.])
>>> A
array([[1.,  0.,  0.],
       [0.,  2.,  0.],
       [0.,  0.,  3.]])
>>> np.fliplr(A)
array([[0.,  0.,  1.],
       [0.,  2.,  0.],
       [3.,  0.,  0.]])
 >>> A = np.random.randn(2,3,5)
>>> np.all(np.fliplr(A) == A[:,::-1,...])
True


numpy.flipud   numpy.flipud(m)[source]

Reverse the order of elements along axis 0 (up/down). For a 2-D array, this flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before.  Parameters

marray_like

Input array.    Returns

outarray_like

A view of m with the rows reversed. Since a view is returned, this operation is \(\mathcal O(1)\).      See also  fliplr

Flip array in the left/right direction.  flip

Flip array in one or more dimensions.  rot90

Rotate array counterclockwise.    Notes Equivalent to m[::-1, ...] or np.flip(m, axis=0). Requires the array to be at least 1-D. Examples >>> A = np.diag([1.0, 2, 3])
>>> A
array([[1.,  0.,  0.],
       [0.,  2.,  0.],
       [0.,  0.,  3.]])
>>> np.flipud(A)
array([[0.,  0.,  3.],
       [0.,  2.,  0.],
       [1.,  0.,  0.]])
 >>> A = np.random.randn(2,3,5)
>>> np.all(np.flipud(A) == A[::-1,...])
True
 >>> np.flipud([1,2])
array([2, 1])


numpy.float96
  numpy.float128[source]

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


numpy.float16[source]

alias of numpy.half


numpy.float32[source]

alias of numpy.single


numpy.float64[source]

alias of numpy.double


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

First array elements raised to powers from second array, element-wise. Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape. This differs from the power function in that integers, float16, and float32 are promoted to floats with a minimum precision of float64 so that the result is always inexact. The intent is that the function will return a usable result for negative powers and seldom overflow for positive powers. Negative values raised to a non-integral value will return nan. To get complex results, cast the input to complex, or specify the dtype to be complex (see the example below).  New in version 1.12.0.   Parameters

x1array_like

The bases.
x2array_like

The exponents. 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

yndarray

The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.      See also  power

power function that preserves type    Examples Cube each element in a list. >>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.float_power(x1, 3)
array([   0.,    1.,    8.,   27.,   64.,  125.])
 Raise the bases to different exponents. >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.float_power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])
 The effect of broadcasting. >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.float_power(x1, x2)
array([[  0.,   1.,   8.,  27.,  16.,   5.],
       [  0.,   1.,   8.,  27.,  16.,   5.]])
 Negative values raised to a non-integral value will result in nan (and a warning will be generated). >>> x3 = np.array([-1, -4])
>>> with np.errstate(invalid='ignore'):
...     p = np.float_power(x3, 1.5)
...
>>> p
array([nan, nan])
 To get complex results, give the argument dtype=complex. >>> np.float_power(x3, 1.5, dtype=complex)
array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])


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

Return the floor of the input, element-wise. The floor of the scalar x is the largest integer i, such that i <= x. It is often denoted as \(\lfloor x \rfloor\).  Parameters

xarray_like

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

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

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

yndarray or scalar

The floor of each element in x. This is a scalar if x is a scalar.      See also
ceil, trunc, rint, fix

  Notes Some spreadsheet programs calculate the “floor-towards-zero”, where floor(-2.5) == -2. NumPy instead uses the definition of floor where floor(-2.5) == -3. The “floor-towards-zero” function is called fix in NumPy. Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.floor(a)
array([-2., -2., -1.,  0.,  1.,  1.,  2.])


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

Return the largest integer smaller or equal to the division of the inputs. It is equivalent to the Python // operator and pairs with the Python % (remainder), function so that a = a % b + b * (a // b) up to roundoff.  Parameters

x1array_like

Numerator.
x2array_like

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

yndarray

y = floor(x1/x2) This is a scalar if both x1 and x2 are scalars.      See also  remainder

Remainder complementary to floor_divide.  divmod

Simultaneous floor division and remainder.  divide

Standard division.  floor

Round a number to the nearest integer toward minus infinity.  ceil

Round a number to the nearest integer toward infinity.    Examples >>> np.floor_divide(7,3)
2
>>> np.floor_divide([1., 2., 3., 4.], 2.5)
array([ 0.,  0.,  1.,  1.])
 The // operator can be used as a shorthand for np.floor_divide on ndarrays. >>> x1 = np.array([1., 2., 3., 4.])
>>> x1 // 2.5
array([0., 0., 1., 1.])


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

Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.  Parameters

x1, x2array_like

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

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

yndarray or scalar

The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.      See also  fmin

Element-wise minimum of two arrays, ignores NaNs.  maximum

Element-wise maximum of two arrays, propagates NaNs.  amax

The maximum value of an array along a given axis, propagates NaNs.  nanmax

The maximum value of an array along a given axis, ignores NaNs.
minimum, amin, nanmin

  Notes  New in version 1.3.0.  The fmax is equivalent to np.where(x1 >= x2, x1, x2) when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples >>> np.fmax([2, 3, 4], [1, 5, 2])
array([ 2.,  5.,  4.])
 >>> np.fmax(np.eye(2), [0.5, 2])
array([[ 1. ,  2. ],
       [ 0.5,  2. ]])
 >>> np.fmax([np.nan, 0, np.nan],[0, np.nan, np.nan])
array([ 0.,  0., nan])


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

Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible.  Parameters

x1, x2array_like

The arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
wherearray_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.  **kwargs

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

yndarray or scalar

The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.      See also  fmax

Element-wise maximum of two arrays, ignores NaNs.  minimum

Element-wise minimum of two arrays, propagates NaNs.  amin

The minimum value of an array along a given axis, propagates NaNs.  nanmin

The minimum value of an array along a given axis, ignores NaNs.
maximum, amax, nanmax

  Notes  New in version 1.3.0.  The fmin is equivalent to np.where(x1 <= x2, x1, x2) when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples >>> np.fmin([2, 3, 4], [1, 5, 2])
array([1, 3, 2])
 >>> np.fmin(np.eye(2), [0.5, 2])
array([[ 0.5,  0. ],
       [ 0. ,  1. ]])
 >>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan])
array([ 0.,  0., nan])


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

Returns the element-wise remainder of division. This is the NumPy implementation of the C library function fmod, the remainder has the same sign as the dividend x1. It is equivalent to the Matlab(TM) rem function and should not be confused with the Python modulus operator x1 % x2.  Parameters

x1array_like

Dividend.
x2array_like

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

yarray_like

The remainder of the division of x1 by x2. This is a scalar if both x1 and x2 are scalars.      See also  remainder

Equivalent to the Python % operator.  divide
  Notes The result of the modulo operation for negative dividend and divisors is bound by conventions. For fmod, the sign of result is the sign of the dividend, while for remainder the sign of the result is the sign of the divisor. The fmod function is equivalent to the Matlab(TM) rem function. Examples >>> np.fmod([-3, -2, -1, 1, 2, 3], 2)
array([-1,  0, -1,  1,  0,  1])
>>> np.remainder([-3, -2, -1, 1, 2, 3], 2)
array([1, 0, 1, 1, 0, 1])
 >>> np.fmod([5, 3], [2, 2.])
array([ 1.,  1.])
>>> a = np.arange(-3, 3).reshape(3, 2)
>>> a
array([[-3, -2],
       [-1,  0],
       [ 1,  2]])
>>> np.fmod(a, [2,2])
array([[-1,  0],
       [-1,  0],
       [ 1,  0]])


numpy.format_float_positional   numpy.format_float_positional(x, precision=None, unique=True, fractional=True, trim='k', sign=False, pad_left=None, pad_right=None, min_digits=None)[source]

Format a floating-point scalar as a decimal string in positional notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the “Dragon4” algorithm.  Parameters

xpython float or numpy floating scalar

Value to format.
precisionnon-negative integer or None, optional

Maximum number of digits to print. May be None if unique is True, but must be an integer if unique is False.
uniqueboolean, optional

If True, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If precision is given fewer digits than necessary can be printed, or if min_digits is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If False, digits are generated as if printing an infinite-precision value and stopping after precision digits, rounding the remaining value with unbiased rounding
fractionalboolean, optional

If True, the cutoffs of precision and min_digits refer to the total number of digits after the decimal point, including leading zeros. If False, precision and min_digits refer to the total number of significant digits, before or after the decimal point, ignoring leading zeros.
trimone of ‘k’, ‘.’, ‘0’, ‘-’, optional

Controls post-processing trimming of trailing digits, as follows:  ‘k’ : keep trailing zeros, keep decimal point (no trimming) ‘.’ : trim all trailing zeros, leave decimal point ‘0’ : trim all but the zero before the decimal point. Insert the zero if it is missing. ‘-’ : trim trailing zeros and any trailing decimal point
signboolean, optional

Whether to show the sign for positive values.
pad_leftnon-negative integer, optional

Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point.
pad_rightnon-negative integer, optional

Pad the right side of the string with whitespace until at least that many characters are to the right of the decimal point.
min_digitsnon-negative integer or None, optional

Minimum number of digits to print. Only has an effect if unique=True in which case additional digits past those necessary to uniquely identify the value may be printed, rounding the last additional digit. – versionadded:: 1.21.0    Returns

repstring

The string representation of the floating point value      See also  format_float_scientific
  Examples >>> np.format_float_positional(np.float32(np.pi))
'3.1415927'
>>> np.format_float_positional(np.float16(np.pi))
'3.14'
>>> np.format_float_positional(np.float16(0.3))
'0.3'
>>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
'0.3000488281'


numpy.format_float_scientific   numpy.format_float_scientific(x, precision=None, unique=True, trim='k', sign=False, pad_left=None, exp_digits=None, min_digits=None)[source]

Format a floating-point scalar as a decimal string in scientific notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the “Dragon4” algorithm.  Parameters

xpython float or numpy floating scalar

Value to format.
precisionnon-negative integer or None, optional

Maximum number of digits to print. May be None if unique is True, but must be an integer if unique is False.
uniqueboolean, optional

If True, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If precision is given fewer digits than necessary can be printed. If min_digits is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If False, digits are generated as if printing an infinite-precision value and stopping after precision digits, rounding the remaining value with unbiased rounding
trimone of ‘k’, ‘.’, ‘0’, ‘-’, optional

Controls post-processing trimming of trailing digits, as follows:  ‘k’ : keep trailing zeros, keep decimal point (no trimming) ‘.’ : trim all trailing zeros, leave decimal point ‘0’ : trim all but the zero before the decimal point. Insert the zero if it is missing. ‘-’ : trim trailing zeros and any trailing decimal point
signboolean, optional

Whether to show the sign for positive values.
pad_leftnon-negative integer, optional

Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point.
exp_digitsnon-negative integer, optional

Pad the exponent with zeros until it contains at least this many digits. If omitted, the exponent will be at least 2 digits.
min_digitsnon-negative integer or None, optional

Minimum number of digits to print. This only has an effect for unique=True. In that case more digits than necessary to uniquely identify the value may be printed and rounded unbiased. – versionadded:: 1.21.0    Returns

repstring

The string representation of the floating point value      See also  format_float_positional
  Examples >>> np.format_float_scientific(np.float32(np.pi))
'3.1415927e+00'
>>> s = np.float32(1.23e24)
>>> np.format_float_scientific(s, unique=False, precision=15)
'1.230000071797338e+24'
>>> np.format_float_scientific(s, exp_digits=4)
'1.23e+0024'


numpy.format_parser   class numpy.format_parser(formats, names, titles, aligned=False, byteorder=None)[source]

Class to convert formats, names, titles description to a dtype. After constructing the format_parser object, the dtype attribute is the converted data-type: dtype = format_parser(formats, names, titles).dtype  Parameters

formatsstr or list of str

The format description, either specified as a string with comma-separated format descriptions in the form 'f8, i4, a5', or a list of format description strings in the form ['f8', 'i4', 'a5'].
namesstr or list/tuple of str

The field names, either specified as a comma-separated string in the form 'col1, col2, col3', or as a list or tuple of strings in the form ['col1', 'col2', 'col3']. An empty list can be used, in that case default field names (‘f0’, ‘f1’, …) are used.
titlessequence

Sequence of title strings. An empty list can be used to leave titles out.
alignedbool, optional

If True, align the fields by padding as the C-compiler would. Default is False.
byteorderstr, optional

If specified, all the fields will be changed to the provided byte-order. Otherwise, the default byte-order is used. For all available string specifiers, see dtype.newbyteorder.      See also
dtype, typename, sctype2char

  Examples >>> np.format_parser(['<f8', '<i4', '<a5'], ['col1', 'col2', 'col3'],
...                  ['T1', 'T2', 'T3']).dtype
dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4'), (('T3', 'col3'), 'S5')])
 names and/or titles can be empty lists. If titles is an empty list, titles will simply not appear. If names is empty, default field names will be used. >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
...                  []).dtype
dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '<S5')])
>>> np.format_parser(['<f8', '<i4', '<a5'], [], []).dtype
dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', 'S5')])
  Attributes

dtypedtype

The converted data-type.


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

Decompose the elements of x into mantissa and twos exponent. Returns (mantissa, exponent), where x = mantissa * 2**exponent`. The mantissa lies in the open interval(-1, 1), while the twos exponent is a signed integer.  Parameters

xarray_like

Array of numbers to be decomposed.
out1ndarray, optional

Output array for the mantissa. Must have the same shape as x.
out2ndarray, optional

Output array for the exponent. Must have the same shape as x.
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

mantissandarray

Floating values between -1 and 1. This is a scalar if x is a scalar.
exponentndarray

Integer exponents of 2. This is a scalar if x is a scalar.      See also  ldexp

Compute y = x1 * 2**x2, the inverse of frexp.    Notes Complex dtypes are not supported, they will raise a TypeError. Examples >>> x = np.arange(9)
>>> y1, y2 = np.frexp(x)
>>> y1
array([ 0.   ,  0.5  ,  0.5  ,  0.75 ,  0.5  ,  0.625,  0.75 ,  0.875,
        0.5  ])
>>> y2
array([0, 1, 2, 2, 3, 3, 3, 3, 4])
>>> y1 * 2**y2
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.])


numpy.frombuffer   numpy.frombuffer(buffer, dtype=float, count=- 1, offset=0, *, like=None)

Interpret a buffer as a 1-dimensional array.  Parameters

bufferbuffer_like

An object that exposes the buffer interface.
dtypedata-type, optional

Data-type of the returned array; default: float.
countint, optional

Number of items to read. -1 means all data in the buffer.
offsetint, optional

Start reading the buffer from this offset (in bytes); default: 0.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

outndarray

   Notes If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.: >>> dt = np.dtype(int)
>>> dt = dt.newbyteorder('>')
>>> np.frombuffer(buf, dtype=dt)
 The data of the resulting array will not be byteswapped, but will be interpreted correctly. Examples >>> s = b'hello world'
>>> np.frombuffer(s, dtype='S1', count=5, offset=6)
array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
 >>> np.frombuffer(b'\x01\x02', dtype=np.uint8)
array([1, 2], dtype=uint8)
>>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
array([1, 2, 3], dtype=uint8)


numpy.fromfile   numpy.fromfile(file, dtype=float, count=- 1, sep='', offset=0, *, like=None)

Construct an array from data in a text or binary file. A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the tofile method can be read using this function.  Parameters

filefile or str or Path

Open file object or filename.  Changed in version 1.17.0: pathlib.Path objects are now accepted.
dtypedata-type

Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file. Most builtin numeric types are supported and extension types may be supported.  New in version 1.18.0: Complex dtypes.
countint

Number of items to read. -1 means all items (i.e., the complete file).
sepstr

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” “) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.
offsetint

The offset (in bytes) from the file’s current position. Defaults to 0. Only permitted for binary files.  New in version 1.17.0.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.       See also
load, save

ndarray.tofile
loadtxt

More flexible way of loading data from a text file.    Notes Do not rely on the combination of tofile and fromfile for data storage, as the binary files generated are not platform independent. In particular, no byte-order or data-type information is saved. Data can be stored in the platform independent .npy format using save and load instead. Examples Construct an ndarray: >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
...                ('temp', float)])
>>> x = np.zeros((1,), dtype=dt)
>>> x['time']['min'] = 10; x['temp'] = 98.25
>>> x
array([((10, 0), 98.25)],
      dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
 Save the raw data to disk: >>> import tempfile
>>> fname = tempfile.mkstemp()[1]
>>> x.tofile(fname)
 Read the raw data from disk: >>> np.fromfile(fname, dtype=dt)
array([((10, 0), 98.25)],
      dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
 The recommended way to store and load data: >>> np.save(fname, x)
>>> np.load(fname + '.npy')
array([((10, 0), 98.25)],
      dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])


numpy.fromfunction   numpy.fromfunction(function, shape, *, dtype=<class 'float'>, like=None, **kwargs)[source]

Construct an array by executing a function over each coordinate. The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).  Parameters

functioncallable

The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis. For example, if shape were (2, 2), then the parameters would be array([[0, 0], [1, 1]]) and array([[0, 1], [0, 1]])
shape(N,) tuple of ints

Shape of the output array, which also determines the shape of the coordinate arrays passed to function.
dtypedata-type, optional

Data-type of the coordinate arrays passed to function. By default, dtype is float.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

fromfunctionany

The result of the call to function is passed back directly. Therefore the shape of fromfunction is completely determined by function. If function returns a scalar value, the shape of fromfunction would not match the shape parameter.      See also
indices, meshgrid

  Notes Keywords other than dtype are passed to function. Examples >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True]])
 >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])


numpy.fromiter   numpy.fromiter(iter, dtype, count=- 1, *, like=None)

Create a new 1-dimensional array from an iterable object.  Parameters

iteriterable object

An iterable object providing data for the array.
dtypedata-type

The data-type of the returned array.
countint, optional

The number of items to read from iterable. The default is -1, which means all data is read.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

outndarray

The output array.     Notes Specify count to improve performance. It allows fromiter to pre-allocate the output array, instead of resizing it on demand. Examples >>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, float)
array([  0.,   1.,   4.,   9.,  16.])


numpy.frompyfunc   numpy.frompyfunc(func, /, nin, nout, *[, identity])

Takes an arbitrary Python function and returns a NumPy ufunc. Can be used, for example, to add broadcasting to a built-in Python function (see Examples section).  Parameters

funcPython function object

An arbitrary Python function.
ninint

The number of input arguments.
noutint

The number of objects returned by func.
identityobject, optional

The value to use for the identity attribute of the resulting object. If specified, this is equivalent to setting the underlying C identity field to PyUFunc_IdentityValue. If omitted, the identity is set to PyUFunc_None. Note that this is _not_ equivalent to setting the identity to None, which implies the operation is reorderable.    Returns

outufunc

Returns a NumPy universal function (ufunc) object.      See also  vectorize

Evaluates pyfunc over input arrays using broadcasting rules of numpy.    Notes The returned ufunc always returns PyObject arrays. Examples Use frompyfunc to add broadcasting to the Python function oct: >>> oct_array = np.frompyfunc(oct, 1, 1)
>>> oct_array(np.array((10, 30, 100)))
array(['0o12', '0o36', '0o144'], dtype=object)
>>> np.array((oct(10), oct(30), oct(100))) # for comparison
array(['0o12', '0o36', '0o144'], dtype='<U5')


numpy.fromregex   numpy.fromregex(file, regexp, dtype, encoding=None)[source]

Construct an array from a text file, using regular expression parsing. The returned array is always a structured array, and is constructed from all matches of the regular expression in the file. Groups in the regular expression are converted to fields of the structured array.  Parameters

filepath or file

Filename or file object to read.  Changed in version 1.22.0: Now accepts os.PathLike implementations.
regexpstr or regexp

Regular expression used to parse the file. Groups in the regular expression correspond to fields in the dtype.
dtypedtype or list of dtypes

Dtype for the structured array; must be a structured datatype.
encodingstr, optional

Encoding used to decode the inputfile. Does not apply to input streams.  New in version 1.14.0.     Returns

outputndarray

The output array, containing the part of the content of file that was matched by regexp. output is always a structured array.    Raises
 TypeError

When dtype is not a valid dtype for a structured array.      See also
fromstring, loadtxt

  Notes Dtypes for structured arrays can be specified in several forms, but all forms specify at least the data type and field name. For details see basics.rec. Examples >>> from io import StringIO
>>> text = StringIO("1312 foo\n1534  bar\n444   qux")
 >>> regexp = r"(\d+)\s+(...)"  # match [digits, whitespace, anything]
>>> output = np.fromregex(text, regexp,
...                       [('num', np.int64), ('key', 'S3')])
>>> output
array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')],
      dtype=[('num', '<i8'), ('key', 'S3')])
>>> output['num']
array([1312, 1534,  444])


numpy.fromstring   numpy.fromstring(string, dtype=float, count=- 1, *, sep, like=None)

A new 1-D array initialized from text data in a string.  Parameters

stringstr

A string containing the data.
dtypedata-type, optional

The data type of the array; default: float. For binary input data, the data must be in exactly this format. Most builtin numeric types are supported and extension types may be supported.  New in version 1.18.0: Complex dtypes.
countint, optional

Read this number of dtype elements from the data. If this is negative (the default), the count will be determined from the length of the data.
sepstr, optional

The string separating numbers in the data; extra whitespace between elements is also ignored.  Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

arrndarray

The constructed array.    Raises
 ValueError

If the string is not the correct size to satisfy the requested dtype and count.      See also
frombuffer, fromfile, fromiter

  Examples >>> np.fromstring('1 2', dtype=int, sep=' ')
array([1, 2])
>>> np.fromstring('1, 2', dtype=int, sep=',')
array([1, 2])


numpy.full   numpy.full(shape, fill_value, dtype=None, order='C', *, like=None)[source]

Return a new array of given shape and type, filled with fill_value.  Parameters

shapeint or sequence of ints

Shape of the new array, e.g., (2, 3) or 2.
fill_valuescalar or array_like

Fill value.
dtypedata-type, optional

 The desired data-type for the array The default, None, means

np.array(fill_value).dtype.
order{‘C’, ‘F’}, optional

Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

outndarray

Array of fill_value with the given shape, dtype, and order.      See also  full_like

Return a new array with shape of input filled with value.  empty

Return a new uninitialized array.  ones

Return a new array setting values to one.  zeros

Return a new array setting values to zero.    Examples >>> np.full((2, 2), np.inf)
array([[inf, inf],
       [inf, inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])
 >>> np.full((2, 2), [1, 2])
array([[1, 2],
       [1, 2]])


numpy.full_like   numpy.full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None)[source]

Return a full array with the same shape and type as a given array.  Parameters

aarray_like

The shape and data-type of a define these same attributes of the returned array.
fill_valuescalar

Fill value.
dtypedata-type, optional

Overrides the data type of the result.
order{‘C’, ‘F’, ‘A’, or ‘K’}, optional

Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible.
subokbool, optional.

If True, then the newly created array will use the sub-class type of a, otherwise it will be a base-class array. Defaults to True.
shapeint or sequence of ints, optional.

Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied.  New in version 1.17.0.     Returns

outndarray

Array of fill_value with the same shape and type as a.      See also  empty_like

Return an empty array with shape and type of input.  ones_like

Return an array of ones with shape and type of input.  zeros_like

Return an array of zeros with shape and type of input.  full

Return a new array of given shape filled with value.    Examples >>> x = np.arange(6, dtype=int)
>>> np.full_like(x, 1)
array([1, 1, 1, 1, 1, 1])
>>> np.full_like(x, 0.1)
array([0, 0, 0, 0, 0, 0])
>>> np.full_like(x, 0.1, dtype=np.double)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
>>> np.full_like(x, np.nan, dtype=np.double)
array([nan, nan, nan, nan, nan, nan])
 >>> y = np.arange(6, dtype=np.double)
>>> np.full_like(y, 0.1)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])


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

Returns the greatest common divisor of |x1| and |x2|  Parameters

x1, x2array_like, int

Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).    Returns

yndarray or scalar

The greatest common divisor of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars.      See also  lcm

The lowest common multiple    Examples >>> np.gcd(12, 20)
4
>>> np.gcd.reduce([15, 25, 35])
5
>>> np.gcd(np.arange(6), 20)
array([20,  1,  2,  1,  4,  5])


numpy.genfromtxt   numpy.genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=" !#$%&'()*+, -./:;<=>?@[\\]^{|}~", replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes', *, like=None)[source]

Load data from a text file, with missing values handled as specified. Each line past the first skip_header lines is split at the delimiter character, and characters following the comments character are discarded.  Parameters

fnamefile, str, pathlib.Path, list of str, generator

File, filename, list, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators must return bytes or strings. The strings in a list or produced by a generator are treated as lines.
dtypedtype, optional

Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually.
commentsstr, optional

The character used to indicate the start of a comment. All the characters occurring on a line after a comment are discarded.
delimiterstr, int, or sequence, optional

The string used to separate values. By default, any consecutive whitespaces act as delimiter. An integer or sequence of integers can also be provided as width(s) of each field.
skiprowsint, optional

skiprows was removed in numpy 1.10. Please use skip_header instead.
skip_headerint, optional

The number of lines to skip at the beginning of the file.
skip_footerint, optional

The number of lines to skip at the end of the file.
convertersvariable, optional

The set of functions that convert the data of a column to a value. The converters can also be used to provide a default value for missing data: converters = {3: lambda s: float(s or 0)}.
missingvariable, optional

missing was removed in numpy 1.10. Please use missing_values instead.
missing_valuesvariable, optional

The set of strings corresponding to missing data.
filling_valuesvariable, optional

The set of values to be used as default when the data are missing.
usecolssequence, optional

Which columns to read, with 0 being the first. For example, usecols = (1, 4, 5) will extract the 2nd, 5th and 6th columns.
names{None, True, str, sequence}, optional

If names is True, the field names are read from the first line after the first skip_header lines. This line can optionally be preceded by a comment delimiter. If names is a sequence or a single-string of comma-separated names, the names will be used to define the field names in a structured dtype. If names is None, the names of the dtype fields will be used, if any.
excludelistsequence, optional

A list of names to exclude. This list is appended to the default list [‘return’,’file’,’print’]. Excluded names are appended with an underscore: for example, file would become file_.
deletecharsstr, optional

A string combining invalid characters that must be deleted from the names.
defaultfmtstr, optional

A format used to define default field names, such as “f%i” or “f_%02i”.
autostripbool, optional

Whether to automatically strip white spaces from the variables.
replace_spacechar, optional

Character(s) used in replacement of white spaces in the variable names. By default, use a ‘_’.
case_sensitive{True, False, ‘upper’, ‘lower’}, optional

If True, field names are case sensitive. If False or ‘upper’, field names are converted to upper case. If ‘lower’, field names are converted to lower case.
unpackbool, optional

If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = genfromtxt(...). When used with a structured data-type, arrays are returned for each field. Default is False.
usemaskbool, optional

If True, return a masked array. If False, return a regular array.
loosebool, optional

If True, do not raise errors for invalid values.
invalid_raisebool, optional

If True, an exception is raised if an inconsistency is detected in the number of columns. If False, a warning is emitted and the offending lines are skipped.
max_rowsint, optional

The maximum number of rows to read. Must not be used with skip_footer at the same time. If given, the value must be at least 1. Default is to read the entire file.  New in version 1.10.0.
encodingstr, optional

Encoding used to decode the inputfile. Does not apply when fname is a file object. The special value ‘bytes’ enables backward compatibility workarounds that ensure that you receive byte arrays when possible and passes latin1 encoded strings to converters. Override this value to receive unicode arrays and pass strings as input to converters. If set to None the system default is used. The default value is ‘bytes’.  New in version 1.14.0.
likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.  New in version 1.20.0.     Returns

outndarray

Data read from the text file. If usemask is True, this is a masked array.      See also  numpy.loadtxt

equivalent function when no data is missing.    Notes  When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any missing data between two fields. When the variables are named (either by a flexible dtype or with names), there must not be any header in the file (else a ValueError exception is raised). Individual values are not stripped of spaces by default. When using a custom converter, make sure the function does remove spaces.  References  1
NumPy User Guide, section I/O with NumPy.   Examples >>> from io import StringIO
>>> import numpy as np
 Comma delimited file with mixed dtype >>> s = StringIO(u"1,1.3,abcde")
>>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
... ('mystring','S5')], delimiter=",")
>>> data
array((1, 1.3, b'abcde'),
      dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
 Using dtype = None >>> _ = s.seek(0) # needed for StringIO example only
>>> data = np.genfromtxt(s, dtype=None,
... names = ['myint','myfloat','mystring'], delimiter=",")
>>> data
array((1, 1.3, b'abcde'),
      dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
 Specifying dtype and names >>> _ = s.seek(0)
>>> data = np.genfromtxt(s, dtype="i8,f8,S5",
... names=['myint','myfloat','mystring'], delimiter=",")
>>> data
array((1, 1.3, b'abcde'),
      dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
 An example with fixed-width columns >>> s = StringIO(u"11.3abcde")
>>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
...     delimiter=[1,3,5])
>>> data
array((1, 1.3, b'abcde'),
      dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', 'S5')])
 An example to show comments >>> f = StringIO('''
... text,# of chars
... hello world,11
... numpy,5''')
>>> np.genfromtxt(f, dtype='S12,S12', delimiter=',')
array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')],
  dtype=[('f0', 'S12'), ('f1', 'S12')])