package scipy

  1. Overview
  2. Docs
Legend:
Library
Module
Module type
Parameter
Class
Class type
val get_py : string -> Py.Object.t

Get an attribute of this module as a Py.Object.t. This is useful to pass a Python function to another function.

val asarray : ?dtype:Np.Dtype.t -> ?order:[ `F | `C ] -> a:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Convert the input to an array.

Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. dtype : data-type, optional By default, the data-type is inferred from the input data. order : 'C', 'F', optional Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to 'C'.

Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray with matching dtype and order. If `a` is a subclass of ndarray, a base class ndarray is returned.

See Also -------- asanyarray : Similar function which passes through subclasses. ascontiguousarray : Convert input to a contiguous array. asfarray : Convert input to a floating point ndarray. asfortranarray : Convert input to an ndarray with column-major memory order. asarray_chkfinite : Similar function which checks input for NaNs and Infs. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions.

Examples -------- Convert a list into an array:

>>> a = 1, 2 >>> np.asarray(a) array(1, 2)

Existing arrays are not copied:

>>> a = np.array(1, 2) >>> np.asarray(a) is a True

If `dtype` is set, array is copied only if dtype does not match:

>>> a = np.array(1, 2, dtype=np.float32) >>> np.asarray(a, dtype=np.float32) is a True >>> np.asarray(a, dtype=np.float64) is a False

Contrary to `asanyarray`, ndarray subclasses are not passed through:

>>> issubclass(np.recarray, np.ndarray) True >>> a = np.array((1.0, 2), (3.0, 4), dtype='f4,i4').view(np.recarray) >>> np.asarray(a) is a False >>> np.asanyarray(a) is a True

val atleast_1d : Py.Object.t list -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Convert inputs to arrays with at least one dimension.

Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

Parameters ---------- arys1, arys2, ... : array_like One or more input arrays.

Returns ------- ret : ndarray An array, or list of arrays, each with ``a.ndim >= 1``. Copies are made only if necessary.

See Also -------- atleast_2d, atleast_3d

Examples -------- >>> np.atleast_1d(1.0) array(1.)

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

>>> np.atleast_1d(1, 3, 4) array([1]), array([3, 4])

val atleast_2d : Py.Object.t list -> Py.Object.t

View inputs as arrays with at least two dimensions.

Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.

Returns ------- res, res2, ... : ndarray An array, or list of arrays, each with ``a.ndim >= 2``. Copies are avoided where possible, and views with two or more dimensions are returned.

See Also -------- atleast_1d, atleast_3d

Examples -------- >>> np.atleast_2d(3.0) array([3.])

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

>>> np.atleast_2d(1, 1, 2, [1, 2]) array([[1]]), array([[1, 2]]), array([[1, 2]])

val callable : Py.Object.t -> Py.Object.t

None

val check_random_state : Py.Object.t -> Py.Object.t

Turn seed into a np.random.RandomState instance

If seed is None (or np.random), return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. If seed is a new-style np.random.Generator, return it. Otherwise raise ValueError.

val cov : ?y:[> `Ndarray ] Np.Obj.t -> ?rowvar:bool -> ?bias:bool -> ?ddof:int -> ?fweights:[ `Ndarray of [> `Ndarray ] Np.Obj.t | `I of int ] -> ?aweights:[> `Ndarray ] Np.Obj.t -> m:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Estimate a covariance matrix, given data and weights.

Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = x_1, x_2, ... x_N^T`, then the covariance matrix element :math:`C_j` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C_i` is the variance of :math:`x_i`.

See the notes for an outline of the algorithm.

Parameters ---------- m : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `m` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same form as that of `m`. rowvar : bool, optional If `rowvar` is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : bool, optional Default normalization (False) is by ``(N - 1)``, where ``N`` is the number of observations given (unbiased estimate). If `bias` is True, then normalization is by ``N``. These values can be overridden by using the keyword ``ddof`` in numpy versions >= 1.5. ddof : int, optional If not ``None`` the default value implied by `bias` is overridden. Note that ``ddof=1`` will return the unbiased estimate, even if both `fweights` and `aweights` are specified, and ``ddof=0`` will return the simple average. See the notes for the details. The default value is ``None``.

.. versionadded:: 1.5 fweights : array_like, int, optional 1-D array of integer frequency weights; the number of times each observation vector should be repeated.

.. versionadded:: 1.10 aweights : array_like, optional 1-D array of observation vector weights. These relative weights are typically large for observations considered 'important' and smaller for observations considered less 'important'. If ``ddof=0`` the array of weights can be used to assign probabilities to observation vectors.

.. versionadded:: 1.10

Returns ------- out : ndarray The covariance matrix of the variables.

See Also -------- corrcoef : Normalized covariance matrix

Notes ----- Assume that the observations are in the columns of the observation array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The steps to compute the weighted covariance are as follows::

>>> m = np.arange(10, dtype=np.float64) >>> f = np.arange(10) * 2 >>> a = np.arange(10) ** 2. >>> ddof = 1 >>> w = f * a >>> v1 = np.sum(w) >>> v2 = np.sum(w * a) >>> m -= np.sum(m * w, axis=None, keepdims=True) / v1 >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)

Note that when ``a == 1``, the normalization factor ``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)`` as it should.

Examples -------- Consider two variables, :math:`x_0` and :math:`x_1`, which correlate perfectly, but in opposite directions:

>>> x = np.array([0, 2], [1, 1], [2, 0]).T >>> x array([0, 1, 2], [2, 1, 0])

Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance matrix shows this clearly:

>>> np.cov(x) array([ 1., -1.], [-1., 1.])

Note that element :math:`C_

,1

`, which shows the correlation between :math:`x_0` and :math:`x_1`, is negative.

Further, note how `x` and `y` are combined:

>>> x = -2.1, -1, 4.3 >>> y = 3, 1.1, 0.12 >>> X = np.stack((x, y), axis=0) >>> np.cov(X) array([11.71 , -4.286 ], # may vary [-4.286 , 2.144133]) >>> np.cov(x, y) array([11.71 , -4.286 ], # may vary [-4.286 , 2.144133]) >>> np.cov(x) array(11.71)

val dot : ?out:[> `Ndarray ] Np.Obj.t -> a:[> `Ndarray ] Np.Obj.t -> b:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

dot(a, b, out=None)

Dot product of two arrays. Specifically,

  • If both `a` and `b` are 1-D arrays, it is inner product of vectors (without complex conjugation).
  • If both `a` and `b` are 2-D arrays, it is matrix multiplication, but using :func:`matmul` or ``a @ b`` is preferred.
  • If either `a` or `b` is 0-D (scalar), it is equivalent to :func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is preferred.
  • If `a` is an N-D array and `b` is a 1-D array, it is a sum product over the last axis of `a` and `b`.
  • If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a sum product over the last axis of `a` and the second-to-last axis of `b`::

dot(a, b)i,j,k,m = sum(ai,j,: * bk,:,m)

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

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

Raises ------ ValueError If the last dimension of `a` is not the same size as the second-to-last dimension of `b`.

See Also -------- vdot : Complex-conjugating dot product. tensordot : Sum products over arbitrary axes. einsum : Einstein summation convention. matmul : '@' operator as method with out parameter.

Examples -------- >>> np.dot(3, 4) 12

Neither argument is complex-conjugated:

>>> np.dot(2j, 3j, 2j, 3j) (-13+0j)

For 2-D arrays it is the matrix product:

>>> a = [1, 0], [0, 1] >>> b = [4, 1], [2, 2] >>> np.dot(a, b) array([4, 1], [2, 2])

>>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) >>> b = np.arange(3*4*5*6)::-1.reshape((5,4,6,3)) >>> np.dot(a, b)2,3,2,1,2,2 499128 >>> sum(a2,3,2,: * b1,2,:,2) 499128

val exp : ?out: [ `Ndarray of [> `Ndarray ] Np.Obj.t | `Tuple_of_ndarray_and_None of Py.Object.t ] -> ?where:[> `Ndarray ] Np.Obj.t -> x:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

exp(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True, signature, extobj)

Calculate the exponential of all elements in the input array.

Parameters ---------- x : array_like Input values. out : ndarray, 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. where : array_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 :ref:`ufunc docs <ufuncs.kwargs>`.

Returns ------- out : ndarray 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 :math:`x = \ln y = \log_e y`, then :math:`e^x = y`. For real input, ``exp(x)`` is always positive.

For complex arguments, ``x = a + ib``, we can write :math:`e^x = e^a e^b`. The first term, :math:`e^a`, is already known (it is the real argument, described above). The second term, :math:`e^b`, is :math:`\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, http://www.math.sfu.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()

val logsumexp : ?axis:int list -> ?b:[> `Ndarray ] Np.Obj.t -> ?keepdims:bool -> ?return_sign:bool -> a:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t * [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Compute the log of the sum of exponentials of input elements.

Parameters ---------- a : array_like Input array. axis : None or int or tuple of ints, optional Axis or axes over which the sum is taken. By default `axis` is None, and all elements are summed.

.. versionadded:: 0.11.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array.

.. versionadded:: 0.15.0 b : array-like, optional Scaling factor for exp(`a`) must be of the same shape as `a` or broadcastable to `a`. These values may be negative in order to implement subtraction.

.. versionadded:: 0.12.0 return_sign : bool, optional If this is set to True, the result will be a pair containing sign information; if False, results that are negative will be returned as NaN. Default is False (no sign information).

.. versionadded:: 0.16.0

Returns ------- res : ndarray The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))`` is returned. sgn : ndarray If return_sign is True, this will be an array of floating-point numbers matching res and +1, 0, or -1 depending on the sign of the result. If False, only one result is returned.

See Also -------- numpy.logaddexp, numpy.logaddexp2

Notes ----- NumPy has a logaddexp function which is very similar to `logsumexp`, but only handles two arguments. `logaddexp.reduce` is similar to this function, but may be less stable.

Examples -------- >>> from scipy.special import logsumexp >>> a = np.arange(10) >>> np.log(np.sum(np.exp(a))) 9.4586297444267107 >>> logsumexp(a) 9.4586297444267107

With weights

>>> a = np.arange(10) >>> b = np.arange(10, 0, -1) >>> logsumexp(a, b=b) 9.9170178533034665 >>> np.log(np.sum(b*np.exp(a))) 9.9170178533034647

Returning a sign flag

>>> logsumexp(1,2,b=1,-1,return_sign=True) (1.5413248546129181, -1.0)

Notice that `logsumexp` does not directly support masked arrays. To use it on a masked array, convert the mask into zero weights:

>>> a = np.ma.array(np.log(2), 2, np.log(3), ... mask=False, True, False) >>> b = (~a.mask).astype(int) >>> logsumexp(a.data, b=b), np.log(5) 1.6094379124341005, 1.6094379124341005

val ones : ?dtype:Np.Dtype.t -> ?order:[ `C | `F ] -> shape:[ `I of int | `Is of int list ] -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

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

Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired 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.

Returns ------- out : ndarray Array of ones with the given shape, dtype, and order.

See Also -------- ones_like : Return an array of ones with shape and type of input. empty : Return a new uninitialized array. zeros : Return a new array setting values to zero. full : Return a new array of given shape filled with value.

Examples -------- >>> np.ones(5) array(1., 1., 1., 1., 1.)

>>> np.ones((5,), dtype=int) array(1, 1, 1, 1, 1)

>>> np.ones((2, 1)) array([1.], [1.])

>>> s = (2,2) >>> np.ones(s) array([1., 1.], [1., 1.])

val power : ?out: [ `Ndarray of [> `Ndarray ] Np.Obj.t | `Tuple_of_ndarray_and_None of Py.Object.t ] -> ?where:[> `Ndarray ] Np.Obj.t -> x:Py.Object.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True, signature, extobj)

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. Note that an integer type raised to a negative integer power will raise a ValueError.

Parameters ---------- x1 : array_like The bases. x2 : array_like The exponents. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes the shape of the output). out : ndarray, 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. where : array_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 :ref:`ufunc docs <ufuncs.kwargs>`.

Returns ------- y : ndarray The bases in `x1` raised to the exponents in `x2`. This is a scalar if both `x1` and `x2` are scalars.

See Also -------- float_power : power function that promotes integers to float

Examples -------- Cube each element in a list.

>>> x1 = range(6) >>> x1 0, 1, 2, 3, 4, 5 >>> np.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.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.power(x1, x2) array([ 0, 1, 8, 27, 16, 5], [ 0, 1, 8, 27, 16, 5])

val ravel : ?order:[ `C | `F | `A | `K ] -> a:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Return a contiguous flattened array.

A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked array will be returned for a masked array input)

Parameters ---------- a : array_like Input array. The elements in `a` are read in the order specified by `order`, and packed as a 1-D array. order : 'C','F', 'A', 'K', optional

The elements of `a` are read using this index order. 'C' means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. 'A' means to read the elements in Fortran-like index order if `a` is Fortran *contiguous* in memory, C-like order otherwise. 'K' means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, 'C' index order is used.

Returns ------- y : array_like y is an array of the same subtype as `a`, with shape ``(a.size,)``. Note that matrices are special cased for backward compatibility, if `a` is a matrix, then y is a 1-D ndarray.

See Also -------- ndarray.flat : 1-D iterator over an array. ndarray.flatten : 1-D array copy of the elements of an array in row-major order. ndarray.reshape : Change the shape of an array without changing its data.

Notes ----- In row-major, C-style order, in two dimensions, the row index varies the slowest, and the column index the quickest. This can be generalized to multiple dimensions, where row-major order implies that the index along the first axis varies slowest, and the index along the last quickest. The opposite holds for column-major, Fortran-style index ordering.

When a view is desired in as many cases as possible, ``arr.reshape(-1)`` may be preferable.

Examples -------- It is equivalent to ``reshape(-1, order=order)``.

>>> x = np.array([1, 2, 3], [4, 5, 6]) >>> np.ravel(x) array(1, 2, 3, 4, 5, 6)

>>> x.reshape(-1) array(1, 2, 3, 4, 5, 6)

>>> np.ravel(x, order='F') array(1, 4, 2, 5, 3, 6)

When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:

>>> np.ravel(x.T) array(1, 4, 2, 5, 3, 6) >>> np.ravel(x.T, order='A') array(1, 2, 3, 4, 5, 6)

When ``order`` is 'K', it will preserve orderings that are neither 'C' nor 'F', but won't reverse axes:

>>> a = np.arange(3)::-1; a array(2, 1, 0) >>> a.ravel(order='C') array(2, 1, 0) >>> a.ravel(order='K') array(2, 1, 0)

>>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a array([[ 0, 2, 4], [ 1, 3, 5]], [[ 6, 8, 10], [ 7, 9, 11]]) >>> a.ravel(order='C') array( 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11) >>> a.ravel(order='K') array( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

val reshape : ?order:[ `C | `F | `A ] -> a:[> `Ndarray ] Np.Obj.t -> newshape:int list -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Gives a new shape to an array without changing its data.

Parameters ---------- a : array_like Array to be reshaped. newshape : int or tuple of ints The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. order : 'C', 'F', 'A', optional Read the elements of `a` using this index order, and place the elements into the reshaped array using this index order. 'C' means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of indexing. 'A' means to read / write the elements in Fortran-like index order if `a` is Fortran *contiguous* in memory, C-like order otherwise.

Returns ------- reshaped_array : ndarray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the *memory layout* (C- or Fortran- contiguous) of the returned array.

See Also -------- ndarray.reshape : Equivalent method.

Notes ----- It is not always possible to change the shape of an array without copying the data. If you want an error to be raised when the data is copied, you should assign the new shape to the shape attribute of the array::

>>> a = np.zeros((10, 2))

# A transpose makes the array non-contiguous >>> b = a.T

# Taking a view makes it possible to modify the shape without modifying # the initial object. >>> c = b.view() >>> c.shape = (20) Traceback (most recent call last): ... AttributeError: incompatible shape for a non-contiguous array

The `order` keyword gives the index ordering both for *fetching* the values from `a`, and then *placing* the values into the output array. For example, let's say you have an array:

>>> a = np.arange(6).reshape((3, 2)) >>> a array([0, 1], [2, 3], [4, 5])

You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.

>>> np.reshape(a, (2, 3)) # C-like index ordering array([0, 1, 2], [3, 4, 5]) >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape array([0, 1, 2], [3, 4, 5]) >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering array([0, 4, 3], [2, 1, 5]) >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F') array([0, 4, 3], [2, 1, 5])

Examples -------- >>> a = np.array([1,2,3], [4,5,6]) >>> np.reshape(a, 6) array(1, 2, 3, 4, 5, 6) >>> np.reshape(a, 6, order='F') array(1, 4, 2, 5, 3, 6)

>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([1, 2], [3, 4], [5, 6])

val sqrt : ?out: [ `Ndarray of [> `Ndarray ] Np.Obj.t | `Tuple_of_ndarray_and_None of Py.Object.t ] -> ?where:[> `Ndarray ] Np.Obj.t -> x:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True, signature, extobj)

Return the non-negative square-root of an array, element-wise.

Parameters ---------- x : array_like The values whose square-roots are required. out : ndarray, 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. where : array_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 :ref:`ufunc docs <ufuncs.kwargs>`.

Returns ------- y : ndarray An array of the same shape as `x`, containing the positive square-root of each element in `x`. If any element in `x` is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in `x` are real, so is `y`, with negative elements returning ``nan``. If `out` was provided, `y` is a reference to it. This is a scalar if `x` is a scalar.

See Also -------- lib.scimath.sqrt A version which returns complex numbers when given negative reals.

Notes ----- *sqrt* has--consistent with common convention--as its branch cut the real 'interval' `-inf`, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous. Examples -------- >>> np.sqrt([1,4,9]) array([ 1., 2., 3.]) >>> np.sqrt([4, -1, -3+4J]) array([ 2.+0.j, 0.+1.j, 1.+2.j]) >>> np.sqrt([4, -1, np.inf]) array([ 2., nan, inf])

val squeeze : ?axis:int list -> a:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Remove single-dimensional entries from the shape of an array.

Parameters ---------- a : array_like Input data. axis : None or int or tuple of ints, optional .. versionadded:: 1.7.0

Selects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised.

Returns ------- squeezed : ndarray The input array, but with all or a subset of the dimensions of length 1 removed. This is always `a` itself or a view into `a`.

Raises ------ ValueError If `axis` is not None, and an axis being squeezed is not of length 1

See Also -------- expand_dims : The inverse operation, adding singleton dimensions reshape : Insert, remove, and combine dimensions, and resize existing ones

Examples -------- >>> x = np.array([[0], [1], [2]]) >>> x.shape (1, 3, 1) >>> np.squeeze(x).shape (3,) >>> np.squeeze(x, axis=0).shape (3, 1) >>> np.squeeze(x, axis=1).shape Traceback (most recent call last): ... ValueError: cannot select an axis to squeeze out which has size not equal to one >>> np.squeeze(x, axis=2).shape (1, 3)

val sum : ?axis:int list -> ?dtype:Np.Dtype.t -> ?out:[> `Ndarray ] Np.Obj.t -> ?keepdims:bool -> ?initial:[ `F of float | `I of int | `Bool of bool | `S of string ] -> ?where:Py.Object.t -> a:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Sum of array elements over a given axis.

Parameters ---------- a : array_like Elements to sum. axis : None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

.. versionadded:: 1.7.0

If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. dtype : dtype, optional The type of the returned array and of the accumulator in which the elements are summed. The dtype of `a` is used by default unless `a` has an integer dtype of less precision than the default platform integer. In that case, if `a` is signed then the platform integer is used while if `a` is unsigned then an unsigned integer of the same precision as the platform integer is used. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

If the default value is passed, then `keepdims` will not be passed through to the `sum` method of sub-classes of `ndarray`, however any non-default value will be. If the sub-class' method does not implement `keepdims` any exceptions will be raised. initial : scalar, optional Starting value for the sum. See `~numpy.ufunc.reduce` for details.

.. versionadded:: 1.15.0

where : array_like of bool, optional Elements to include in the sum. See `~numpy.ufunc.reduce` for details.

.. versionadded:: 1.17.0

Returns ------- sum_along_axis : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar is returned. If an output array is specified, a reference to `out` is returned.

See Also -------- ndarray.sum : Equivalent method.

add.reduce : Equivalent functionality of `add`.

cumsum : Cumulative sum of array elements.

trapz : Integration of array values using the composite trapezoidal rule.

mean, average

Notes ----- Arithmetic is modular when using integer types, and no error is raised on overflow.

The sum of an empty array is the neutral element 0:

>>> np.sum() 0.0

For floating point numbers the numerical precision of sum (and ``np.add.reduce``) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no ``axis`` is given. When ``axis`` is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python's ``math.fsum`` function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as ``float32``, numerical errors can become significant. In such cases it can be advisable to use `dtype='float64'` to use a higher precision for the output.

Examples -------- >>> np.sum(0.5, 1.5) 2.0 >>> np.sum(0.5, 0.7, 0.2, 1.5, dtype=np.int32) 1 >>> np.sum([0, 1], [0, 5]) 6 >>> np.sum([0, 1], [0, 5], axis=0) array(0, 6) >>> np.sum([0, 1], [0, 5], axis=1) array(1, 5) >>> np.sum([0, 1], [np.nan, 5], where=False, True, axis=1) array(1., 5.)

If the accumulator is too small, overflow occurs:

>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) -128

You can also start the sum with a value other than zero:

>>> np.sum(10, initial=5) 15

val transpose : ?axes:Py.Object.t -> a:[> `Ndarray ] Np.Obj.t -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

Permute the dimensions of an array.

Parameters ---------- a : array_like Input array. axes : list of ints, optional By default, reverse the dimensions, otherwise permute the axes according to the values given.

Returns ------- p : ndarray `a` with its axes permuted. A view is returned whenever possible.

See Also -------- moveaxis argsort

Notes ----- Use `transpose(a, argsort(axes))` to invert the transposition of tensors when using the `axes` keyword argument.

Transposing a 1-D array returns an unchanged view of the original array.

Examples -------- >>> x = np.arange(4).reshape((2,2)) >>> x array([0, 1], [2, 3])

>>> np.transpose(x) array([0, 2], [1, 3])

>>> x = np.ones((1, 2, 3)) >>> np.transpose(x, (1, 0, 2)).shape (2, 1, 3)

val zeros : ?dtype:Np.Dtype.t -> ?order:[ `C | `F ] -> shape:int list -> unit -> [ `ArrayLike | `Ndarray | `Object ] Np.Obj.t

zeros(shape, dtype=float, order='C')

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

Parameters ---------- shape : int or tuple of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired 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.

Returns ------- out : ndarray Array of zeros with the given shape, dtype, and order.

See Also -------- zeros_like : Return an array of zeros with shape and type of input. empty : Return a new uninitialized array. ones : Return a new array setting values to one. full : Return a new array of given shape filled with value.

Examples -------- >>> np.zeros(5) array( 0., 0., 0., 0., 0.)

>>> np.zeros((5,), dtype=int) array(0, 0, 0, 0, 0)

>>> np.zeros((2, 1)) array([ 0.], [ 0.])

>>> s = (2,2) >>> np.zeros(s) array([ 0., 0.], [ 0., 0.])

>>> np.zeros((2,), dtype=('x', 'i4'), ('y', 'i4')) # custom dtype array((0, 0), (0, 0), dtype=('x', '<i4'), ('y', '<i4'))

OCaml

Innovation. Community. Security.