A Legendre series class.
The Legendre class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the attributes and methods listed in the ABCPolyBase documentation.
Legendre coefficients in order of increasing degree, i.e., (1, 2, 3) gives 1*P_0(x) + 2*P_1(x) + 3*P_2(x).
Domain to use. The interval [domain[0], domain[1]] is mapped to the interval [window[0], window[1]] by shifting and scaling. The default value is [-1, 1].
Window, see domain for its use. The default value is [-1, 1].
New in version 1.6.0.
__call__(arg)
Call self as a function.
basis(deg[, domain, window])
Series basis polynomial of degree deg.
cast(series[, domain, window])
Convert series to series of this class.
convert([domain, kind, window])
Convert series to a different kind and/or domain and/or window.
copy()
Return a copy.
cutdeg(deg)
Truncate series to the given degree.
degree()
The degree of the series.
deriv([m])
Differentiate.
fit(x, y, deg[, domain, rcond, full, w, window])
Least squares fit to data.
fromroots(roots[, domain, window])
Return series instance that has the specified roots.
has_samecoef(other)
Check if coefficients match.
has_samedomain(other)
Check if domains match.
has_sametype(other)
Check if types match.
has_samewindow(other)
Check if windows match.
identity([domain, window])
Identity function.
integ([m, k, lbnd])
Integrate.
linspace([n, domain])
Return x, y values at equally spaced points in domain.
mapparms()
Return the mapping parameters.
roots()
Return the roots of the series polynomial.
trim([tol])
Remove trailing coefficients
truncate(size)
Truncate series to length size.


A power series class.
The Polynomial class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the attributes and methods listed in the ABCPolyBase documentation.
Polynomial coefficients in order of increasing degree, i.e., (1, 2, 3) give 1 + 2*x + 3*x**2.
Domain to use. The interval [domain[0], domain[1]] is mapped to the interval [window[0], window[1]] by shifting and scaling. The default value is [-1, 1].
Window, see domain for its use. The default value is [-1, 1].
New in version 1.6.0.
__call__(arg)
Call self as a function.
basis(deg[, domain, window])
Series basis polynomial of degree deg.
cast(series[, domain, window])
Convert series to series of this class.
convert([domain, kind, window])
Convert series to a different kind and/or domain and/or window.
copy()
Return a copy.
cutdeg(deg)
Truncate series to the given degree.
degree()
The degree of the series.
deriv([m])
Differentiate.
fit(x, y, deg[, domain, rcond, full, w, window])
Least squares fit to data.
fromroots(roots[, domain, window])
Return series instance that has the specified roots.
has_samecoef(other)
Check if coefficients match.
has_samedomain(other)
Check if domains match.
has_sametype(other)
Check if types match.
has_samewindow(other)
Check if windows match.
identity([domain, window])
Identity function.
integ([m, k, lbnd])
Integrate.
linspace([n, domain])
Return x, y values at equally spaced points in domain.
mapparms()
Return the mapping parameters.
roots()
Return the roots of the series polynomial.
trim([tol])
Remove trailing coefficients
truncate(size)
Truncate series to length size.


Difference (subtraction) of two polynomials.
Note
This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.
Given two polynomials a1 and a2, returns a1 - a2. a1 and a2 can be either array_like sequences of the polynomials’ coefficients (including coefficients equal to zero), or poly1d objects.
Minuend and subtrahend polynomials, respectively.
Array or poly1d object of the difference polynomial’s coefficients.
See also


Evaluate a polynomial at specific values.
Note
This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.
If p is of length N, this function returns the value:
p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]
If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.
1D array of polynomial coefficients (including coefficients equal to zero) from highest degree to the constant term, or an instance of poly1d.
A number, an array of numbers, or an instance of poly1d, at which to evaluate p.
If x is a poly1d instance, the result is the composition of the two polynomials, i.e., x is “substituted” in p and the simplified result is returned. In addition, the type of x - array_like or poly1d - governs the type of the output: x array_like => values array_like, x a poly1d object => values is also.
See also
A polynomial class.
Horner’s scheme [1] is used to evaluate the polynomial. Even so, for polynomials of high degree the values may be inaccurate due to rounding errors. Use carefully.
If x is a subtype of ndarray the return value will be of the same type.
I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng. trans. Ed.), Handbook of Mathematics, New York, Van Nostrand Reinhold Co., 1985, pg. 720.


Numerical positive, element-wise.
New in version 1.13.0.
Input array.
Returned array or scalar: y = +x. This is a scalar if x is a scalar.
Equivalent to x.copy(), but only defined for types that support arithmetic.
The unary + operator can be used as a shorthand for np.positive on ndarrays.


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.
An integer type raised to a negative integer power will raise a ValueError.
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).
The bases.
The exponents. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
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.
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.
For other keyword-only arguments, see the ufunc docs.
The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.
See also
power function that promotes integers to float
Cube each element in an array.
Raise the bases to different exponents.
The effect of broadcasting.
The ** operator can be used as a shorthand for np.power on ndarrays.
Negative values raised to a non-integral value will result in nan (and a warning will be generated).
To get complex results, give the argument dtype=complex.


Context manager for setting print options.
Set print options for the scope of the with block, and restore the old options at the end. See set_printoptions for the full description of available options.
See also
The as-clause of the with-statement gives the current print options:


Return the product of array elements over a given axis.
Input data.
Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.
New in version 1.7.0.
If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
The type of the returned array, as well as of the accumulator in which the elements are multiplied. 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.
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.
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 prod 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.
The starting value for this product. See reduce for details.
New in version 1.15.0.
Elements to include in the product. See reduce for details.
New in version 1.17.0.
An array shaped as a but with the specified axis removed. Returns a reference to out if specified.
See also
equivalent method
Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit platform:
The product of an empty array is the neutral element 1:
By default, calculate the product of all elements:
Even when the input array is two-dimensional:
But we can also specify the axis over which to multiply:
Or select specific elements to include:
If the type of x is unsigned, then the output type is the unsigned platform integer:
If x is of a signed integer type, then the output type is the default platform integer:
You can also start the product with a value other than one:


Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 may be safely cast. The returned data type is always in native byte order.
This function is symmetric, but rarely associative.
First data type.
Second data type.
The promoted data type.
See also
New in version 1.6.0.
Starting in NumPy 1.9, promote_types function now returns a valid string length when given an integer or float dtype as one argument and a string dtype as another argument. Previously it always returned the input string dtype, even if it wasn’t long enough to store the max integer/float value converted to a string.
An example of a non-associative case:


Range of values (maximum - minimum) along an axis.
The name of the function comes from the acronym for ‘peak to peak’.
Warning
ptp preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than 2**(n-1)-1 will be returned as negative values. An example with a work-around is shown below.
Input values.
Axis along which to find the peaks. By default, flatten the array. axis may be negative, in which case it counts from the last to the first axis.
New in version 1.15.0.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type of the output values will be cast if necessary.
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 ptp 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.
A new array holding the result, unless out was specified, in which case a reference to out is returned.
This example shows that a negative value can be returned when the input is an array of signed integers.
A work-around is to use the view() method to view the result as unsigned integers with the same bit width:


Replaces specified elements of an array with given values.
The indexing works on the flattened target array. put is roughly equivalent to:
Target array.
Target indices, interpreted as integers.
Values to place in a at target indices. If v is shorter than ind it will be repeated as necessary.
Specifies how out-of-bounds indices will behave.
‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. In ‘raise’ mode, if an exception occurs the target array may still be modified.
See also
Put elements by matching the array and the index arrays


Put values into the destination array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to place values into the latter. These slices can be different lengths.
Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function.
New in version 1.15.0.
Destination array.
Indices to change along each 1d slice of arr. This must match the dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast against arr.
values to insert at those indices. Its shape and dimension are broadcast to match that of indices.
The axis to take 1d slices along. If axis is None, the destination array is treated as if a flattened 1d view had been created of it.
See also
Take values from the input array by matching 1d index and data slices
This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii and kk to a tuple of indices:
Equivalently, eliminating the inner loop, the last two lines would be:
For this sample array
We can replace the maximum values with:


Changes elements of an array based on conditional and input values.
Sets a.flat[n] = values[n] for each n where mask.flat[n]==True.
If values is not the same size as a and mask then it will repeat. This gives behavior different from a[mask] = values.
Target array.
Boolean mask array. It has to be the same shape as a.
Values to put into a where mask is True. If values is smaller than a it will be repeated.
See also
If values is smaller than a it is repeated:


IEEE 754 floating point representation of positive zero.
A floating point representation of positive zero.
NZERO : Defines negative zero.
isinf : Shows which elements are positive or negative infinity.
isposinf : Shows which elements are positive infinity.
isneginf : Shows which elements are negative infinity.
isnan : Shows which elements are Not a Number.
Not a Number, positive infinity and negative infinity.
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Positive zero is considered to be a finite number.


Compute the q-th quantile of the data along the specified axis.
New in version 1.15.0.
Input array or object that can be converted to an array.
Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.
Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.
Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.
If True, then allow the input array a to be modified by intermediate calculations, to save memory. In this case, the contents of the input a after this function completes is undefined.
This parameter specifies the method to use for estimating the quantile. There are many different methods, some unique to NumPy. See the notes for explanation. The options sorted by their R type as summarized in the H&F paper [1] are:
The first three methods are discontiuous. NumPy further defines the following discontinuous variations of the default ‘linear’ (7.) option:
Changed in version 1.22.0: This argument was previously called “interpolation” and only offered the “linear” default and last four options.
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 a.
Deprecated name for the method keyword argument.
Deprecated since version 1.22.0.
If q is a single quantile and axis=None, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.
See also
equivalent to quantile, but with q in the range [0, 100].
equivalent to quantile(..., 0.5)
Given a vector V of length N, the q-th quantile of V is the value q of the way from the minimum to the maximum in a sorted copy of V. The values and distances of the two nearest neighbors as well as the method parameter will determine the quantile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=0.5, the same as the minimum if q=0.0 and the same as the maximum if q=1.0.
This optional method parameter specifies the method to use when the desired quantile lies between two data points i < j. If g is the fractional part of the index surrounded by i and alpha and beta are correction constants modifying i and j.
The different methods then work as follows
method 1 of H&F [1]. This method gives discontinuous results: * if g > 0 ; then take j * if g = 0 ; then take i
method 2 of H&F [1]. This method give discontinuous results: * if g > 0 ; then take j * if g = 0 ; then average between bounds
method 3 of H&F [1]. This method give discontinuous results: * if g > 0 ; then take j * if g = 0 and index is odd ; then take j * if g = 0 and index is even ; then take i
method 4 of H&F [1]. This method give continuous results using: * alpha = 0 * beta = 1
method 5 of H&F [1]. This method give continuous results using: * alpha = 1/2 * beta = 1/2
method 6 of H&F [1]. This method give continuous results using: * alpha = 0 * beta = 0
method 7 of H&F [1]. This method give continuous results using: * alpha = 1 * beta = 1
method 8 of H&F [1]. This method is probably the best method if the sample distribution function is unknown (see reference). This method give continuous results using: * alpha = 1/3 * beta = 1/3
method 9 of H&F [1]. This method is probably the best method if the sample distribution function is known to be normal. This method give continuous results using: * alpha = 3/8 * beta = 3/8
NumPy method kept for backwards compatibility. Takes i as the interpolation point.
NumPy method kept for backwards compatibility. Takes j as the interpolation point.
NumPy method kept for backwards compatibility. Takes i or j, whichever is nearest.
NumPy method kept for backwards compatibility. Uses (i + j) / 2.
R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages,” The American Statistician, 50(4), pp. 361-365, 1996
See also numpy.percentile for a visualization of most methods.


Translates slice objects to concatenation along the first axis.
This is a simple way to build up arrays quickly. There are two use cases.
If slice notation is used, the syntax start:stop:step is equivalent to np.arange(start, stop, step) inside of the brackets. However, if step is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive. In other words start:stop:stepj is interpreted as np.linspace(start, stop, step, endpoint=1) inside of the brackets. After expansion of slice notation, all comma separated sequences are concatenated together.
Optional character strings placed as the first element of the index expression can be used to change the output. The strings ‘r’ or ‘c’ result in matrix output. If the result is 1-D and ‘r’ is specified a 1 x N (row) matrix is produced. If the result is 1-D and ‘c’ is specified, then a N x 1 (column) matrix is produced. If the result is 2-D then both provide the same matrix result.
A string integer specifies which axis to stack multiple comma separated arrays along. A string of two comma-separated integers allows indication of the minimum number of dimensions to force each entry into as the second integer (the axis to concatenate along is still the first integer).
A string with three comma-separated integers allows specification of the axis to concatenate along, the minimum number of dimensions to force the entries to, and which axis should contain the start of the arrays which are less than the specified number of dimensions. In other words the third integer allows you to specify where the 1’s should be placed in the shape of the arrays that have their shapes upgraded. By default, they are placed in the front of the shape tuple. The third argument allows you to specify where the start of the array should be instead. Thus, a third argument of ‘0’ would place the 1’s at the end of the array shape. Negative integers specify where in the new shape tuple the last dimension of upgraded arrays should be placed, so the default is ‘-1’.
See also
Join a sequence of arrays along an existing axis.
Translates slice objects to concatenation along the second axis.
String integers specify the axis to concatenate along or the minimum number of dimensions to force entries into.
Using ‘r’ or ‘c’ as a first string argument creates a matrix.


Convert angles from radians to degrees.
Angle in radians.
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.
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.
For other keyword-only arguments, see the ufunc docs.
The corresponding angle in degrees. This is a scalar if x is a scalar.
See also
Convert angles from degrees to radians.
Remove large jumps in angle by wrapping.
New in version 1.3.0.
rad2deg(x) is 180 * x / pi.


Convert angles from degrees to radians.
Input array in degrees.
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.
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.
For other keyword-only arguments, see the ufunc docs.
The corresponding radian values. This is a scalar if x is a scalar.
See also
equivalent function
Convert a degree array to radians


Base Class for generic BitGenerators, which provide a stream of random bits based on different algorithms. Must be overridden.
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to ~`numpy.random.SeedSequence` to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
See also
Lock instance that is shared so that the same BitGenerator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock.
random_raw(self[, size])
Return randoms as generated by the underlying BitGenerator


The Generator provides access to a wide range of distributions, and served as a replacement for RandomState. The main difference between the two is that Generator relies on an additional BitGenerator to manage state and generate the random bits, which are then transformed into random values from useful distributions. The default BitGenerator used by Generator is PCG64. The BitGenerator can be changed by passing an instantized BitGenerator to Generator.
Construct a new Generator with the default BitGenerator (PCG64).
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Additionally, when passed a BitGenerator, it will be wrapped by Generator. If passed a Generator, it will be returned unaltered.
The initialized generator object.
If seed is not a BitGenerator or a Generator, a new BitGenerator is instantiated. This function does not manage a default global instance.
default_rng is the recommended constructor for the random number class Generator. Here are several ways we can construct a random number generator using default_rng and the Generator class.
Here we use default_rng to generate a random float:
Here we use default_rng to generate 3 random integers between 0 (inclusive) and 10 (exclusive):
Here we specify a seed so that we have reproducible results:
If we exit and restart our Python interpreter, we’ll see that we generate the same random numbers again:
Container for the BitGenerators.
Generator exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned.
The function numpy.random.default_rng will instantiate a Generator with numpy’s default BitGenerator.
No Compatibility Guarantee
Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change.
BitGenerator to use as the core generator.
See also
Recommended constructor for Generator.
The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator. It uses Mersenne Twister, and this bit generator can be accessed using MT19937. Generator, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.
bit_generator
Gets the bit generator instance used by the generator
integers(low[, high, size, dtype, endpoint])
Return random integers from low (inclusive) to high (exclusive), or if endpoint=True, low (inclusive) to high (inclusive).
random([size, dtype, out])
Return random floats in the half-open interval [0.0, 1.0).
choice(a[, size, replace, p, axis, shuffle])
Generates a random sample from a given array
bytes(length)
Return random bytes.
The methods for randomly permuting a sequence are
shuffle(x[, axis])
Modify an array or sequence in-place by shuffling its contents.
permutation(x[, axis])
Randomly permute a sequence, or return a permuted range.
permuted(x[, axis, out])
Randomly permute x along axis axis.
The following table summarizes the behaviors of the methods.
method
copy/in-place
axis handling
shuffle
in-place
as if 1d
permutation
copy
as if 1d
permuted
either (use ‘out’ for in-place)
axis independent
The following subsections provide more details about the differences.
The main difference between Generator.shuffle and Generator.permutation is that Generator.shuffle operates in-place, while Generator.permutation returns a copy.
By default, Generator.permuted returns a copy. To operate in-place with Generator.permuted, pass the same array as the first argument and as the value of the out parameter. For example,
Note that when out is given, the return value is out:
An important distinction for these methods is how they handle the axis parameter. Both Generator.shuffle and Generator.permutation treat the input as a one-dimensional sequence, and the axis parameter determines which dimension of the input array to use as the sequence. In the case of a two-dimensional array, axis=0 will, in effect, rearrange the rows of the array, and axis=1 will rearrange the columns. For example
Note that the columns have been rearranged “in bulk”: the values within each column have not changed.
The method Generator.permuted treats the axis parameter similar to how numpy.sort treats it. Each slice along the given axis is shuffled independently of the others. Compare the following example of the use of Generator.permuted to the above example of Generator.permutation:
In this example, the values within each row (i.e. the values along axis=1) have been shuffled independently. This is not a “bulk” shuffle of the columns.
Generator.shuffle works on non-NumPy sequences. That is, if it is given a sequence that is not a NumPy array, it shuffles that sequence in-place. For example,
beta(a, b[, size])
Draw samples from a Beta distribution.
binomial(n, p[, size])
Draw samples from a binomial distribution.
chisquare(df[, size])
Draw samples from a chi-square distribution.
dirichlet(alpha[, size])
Draw samples from the Dirichlet distribution.
exponential([scale, size])
Draw samples from an exponential distribution.
f(dfnum, dfden[, size])
Draw samples from an F distribution.
gamma(shape[, scale, size])
Draw samples from a Gamma distribution.
geometric(p[, size])
Draw samples from the geometric distribution.
gumbel([loc, scale, size])
Draw samples from a Gumbel distribution.
hypergeometric(ngood, nbad, nsample[, size])
Draw samples from a Hypergeometric distribution.
laplace([loc, scale, size])
Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
logistic([loc, scale, size])
Draw samples from a logistic distribution.
lognormal([mean, sigma, size])
Draw samples from a log-normal distribution.
logseries(p[, size])
Draw samples from a logarithmic series distribution.
multinomial(n, pvals[, size])
Draw samples from a multinomial distribution.
multivariate_hypergeometric(colors, nsample)
Generate variates from a multivariate hypergeometric distribution.
multivariate_normal(mean, cov[, size, ...])
Draw random samples from a multivariate normal distribution.
negative_binomial(n, p[, size])
Draw samples from a negative binomial distribution.
noncentral_chisquare(df, nonc[, size])
Draw samples from a noncentral chi-square distribution.
noncentral_f(dfnum, dfden, nonc[, size])
Draw samples from the noncentral F distribution.
normal([loc, scale, size])
Draw random samples from a normal (Gaussian) distribution.
pareto(a[, size])
Draw samples from a Pareto II or Lomax distribution with specified shape.
poisson([lam, size])
Draw samples from a Poisson distribution.
power(a[, size])
Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
rayleigh([scale, size])
Draw samples from a Rayleigh distribution.
standard_cauchy([size])
Draw samples from a standard Cauchy distribution with mode = 0.
standard_exponential([size, dtype, method, out])
Draw samples from the standard exponential distribution.
standard_gamma(shape[, size, dtype, out])
Draw samples from a standard Gamma distribution.
standard_normal([size, dtype, out])
Draw samples from a standard Normal distribution (mean=0, stdev=1).
standard_t(df[, size])
Draw samples from a standard Student's t distribution with df degrees of freedom.
triangular(left, mode, right[, size])
Draw samples from the triangular distribution over the interval [left, right].
uniform([low, high, size])
Draw samples from a uniform distribution.
vonmises(mu, kappa[, size])
Draw samples from a von Mises distribution.
wald(mean, scale[, size])
Draw samples from a Wald, or inverse Gaussian, distribution.
weibull(a[, size])
Draw samples from a Weibull distribution.
zipf(a[, size])
Draw samples from a Zipf distribution.


Container for the BitGenerators.
Generator exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned.
The function numpy.random.default_rng will instantiate a Generator with numpy’s default BitGenerator.
No Compatibility Guarantee
Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change.
BitGenerator to use as the core generator.
See also
Recommended constructor for Generator.
The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator. It uses Mersenne Twister, and this bit generator can be accessed using MT19937. Generator, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.


Container for the Mersenne Twister pseudo-random number generator.
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
MT19937 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers [1]. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access.
The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator.
State and Seeding
The MT19937 state vector consists of a 624-element array of 32-bit unsigned integers plus a single integer value between 0 and 624 that indexes the current position within the main array.
The input seed is processed by SeedSequence to fill the whole state. The first element is reset such that only its most significant bit is set.
Parallel Features
The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators:
Another method is to use MT19937.jumped which advances the state as-if \(2^{128}\) random numbers have been generated ([1], [2]). This allows the original sequence to be split so that distinct segments can be used in each worker process. All generators should be chained to ensure that the segments come from the same sequence.
Compatibility Guarantee
MT19937 makes a guarantee that a fixed seed and will always produce the same random integer stream.
Hiroshi Haramoto, Makoto Matsumoto, and Pierre L’Ecuyer, “A Fast Jump Ahead Algorithm for Linear Recurrences in a Polynomial Space”, Sequences and Their Applications - SETA, 290–298, 2008.
Hiroshi Haramoto, Makoto Matsumoto, Takuji Nishimura, François Panneton, Pierre L’Ecuyer, “Efficient Jump Ahead for F2-Linear Random Number Generators”, INFORMS JOURNAL ON COMPUTING, Vol. 20, No. 3, Summer 2008, pp. 385-390.
Lock instance that is shared so that the same bit git generator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock.
state
Get or set the PRNG state
jumped([jumps])
Returns a new bit generator with the state jumped
cffi
CFFI interface
ctypes
ctypes interface


BitGenerator for the PCG-64 pseudo-random number generator.
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
PCG-64 is a 128-bit implementation of O’Neill’s permutation congruential generator ([1], [2]). PCG-64 has a period of \(2^{128}\) and supports advancing an arbitrary number of steps as well as \(2^{127}\) streams. The specific member of the PCG family that we use is PCG XSL RR 128/64 as described in the paper ([2]).
PCG64 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access.
Supports the method advance to advance the RNG an arbitrary number of steps. The state of the PCG-64 RNG is represented by 2 128-bit unsigned integers.
State and Seeding
The PCG64 state vector consists of 2 unsigned 128-bit values, which are represented externally as Python ints. One is the state of the PRNG, which is advanced by a linear congruential generator (LCG). The second is a fixed odd increment used in the LCG.
The input seed is processed by SeedSequence to generate both values. The increment is not independently settable.
Parallel Features
The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators:
Compatibility Guarantee
PCG64 makes a guarantee that a fixed seed will always produce the same random integer stream.
“PCG, A Family of Better Random Number Generators”
O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation”
state
Get or set the PRNG state
advance(delta)
Advance the underlying RNG as-if delta draws have occurred.
jumped([jumps])
Returns a new bit generator with the state jumped.
cffi
CFFI interface
ctypes
ctypes interface


BitGenerator for the PCG-64 DXSM pseudo-random number generator.
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
PCG-64 DXSM is a 128-bit implementation of O’Neill’s permutation congruential generator ([1], [2]). PCG-64 DXSM has a period of \(2^{128}\) and supports advancing an arbitrary number of steps as well as \(2^{127}\) streams. The specific member of the PCG family that we use is PCG CM DXSM 128/64. It differs from PCG64 in that it uses the stronger DXSM output function, a 64-bit “cheap multiplier” in the LCG, and outputs from the state before advancing it rather than advance-then-output.
PCG64DXSM provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access.
Supports the method advance to advance the RNG an arbitrary number of steps. The state of the PCG-64 DXSM RNG is represented by 2 128-bit unsigned integers.
State and Seeding
The PCG64DXSM state vector consists of 2 unsigned 128-bit values, which are represented externally as Python ints. One is the state of the PRNG, which is advanced by a linear congruential generator (LCG). The second is a fixed odd increment used in the LCG.
The input seed is processed by SeedSequence to generate both values. The increment is not independently settable.
Parallel Features
The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators:
Compatibility Guarantee
PCG64DXSM makes a guarantee that a fixed seed will always produce the same random integer stream.
“PCG, A Family of Better Random Number Generators”
O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation”
state
Get or set the PRNG state
advance(delta)
Advance the underlying RNG as-if delta draws have occurred.
jumped([jumps])
Returns a new bit generator with the state jumped.
cffi
CFFI interface
ctypes
ctypes interface


Container for the Philox (4x64) pseudo-random number generator.
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
Counter to use in the Philox state. Can be either a Python int (long in 2.x) in [0, 2**256) or a 4-element uint64 array. If not provided, the RNG is initialized at 0.
Key to use in the Philox state. Unlike seed, the value in key is directly set. Can be either a Python int in [0, 2**128) or a 2-element uint64 array. key and seed cannot both be used.
Philox is a 64-bit PRNG that uses a counter-based design based on weaker (and faster) versions of cryptographic functions [1]. Instances using different values of the key produce independent sequences. Philox has a period of \(2^{256} - 1\) and supports arbitrary advancing and jumping the sequence in increments of \(2^{128}\). These features allow multiple non-overlapping sequences to be generated.
Philox provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access.
State and Seeding
The Philox state vector consists of a 256-bit value encoded as a 4-element uint64 array and a 128-bit value encoded as a 2-element uint64 array. The former is a counter which is incremented by 1 for every 4 64-bit randoms produced. The second is a key which determined the sequence produced. Using different keys produces independent sequences.
The input seed is processed by SeedSequence to generate the key. The counter is set to 0.
Alternately, one can omit the seed parameter and set the key and counter directly.
Parallel Features
The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators:
Philox can be used in parallel applications by calling the jumped method to advances the state as-if \(2^{128}\) random numbers have been generated. Alternatively, advance can be used to advance the counter for any positive step in [0, 2**256). When using jumped, all generators should be chained to ensure that the segments come from the same sequence.
Alternatively, Philox can be used in parallel applications by using a sequence of distinct keys where each instance uses different key.
Compatibility Guarantee
Philox makes a guarantee that a fixed seed will always produce the same random integer stream.
John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, “Parallel Random Numbers: As Easy as 1, 2, 3,” Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011.
Lock instance that is shared so that the same bit git generator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock.
state
Get or set the PRNG state
advance(delta)
Advance the underlying RNG as-if delta draws have occurred.
jumped([jumps])
Returns a new bit generator with the state jumped
cffi
CFFI interface
ctypes
ctypes interface


The RandomState provides access to legacy generators. This generator is considered frozen and will have no further improvements. It is guaranteed to produce the same values as the final point release of NumPy v1.16. These all depend on Box-Muller normals or inverse CDF exponentials or gammas. This class should only be used if it is essential to have randoms that are identical to what would have been produced by previous versions of NumPy.
RandomState adds additional information to the state which is required when using Box-Muller normals since these are produced in pairs. It is important to use RandomState.get_state, and not the underlying bit generators state, when accessing the state so that these extra values are saved.
Although we provide the MT19937 BitGenerator for use independent of RandomState, note that its default seeding uses SeedSequence rather than the legacy seeding algorithm. RandomState will use the legacy seeding algorithm. The methods to use the legacy seeding algorithm are currently private as the main reason to use them is just to implement RandomState. However, one can reset the state of MT19937 using the state of the RandomState:
Container for the slow Mersenne Twister pseudo-random number generator. Consider using a different BitGenerator with the Generator container instead.
RandomState and Generator expose a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned.
Compatibility Guarantee
A fixed bit generator using a fixed seed and a fixed series of calls to ‘RandomState’ methods using the same parameters will always produce the same results up to roundoff error except when the values were incorrect. RandomState is effectively frozen and will only receive updates that are required by changes in the the internals of Numpy. More substantial changes, including algorithmic improvements, are reserved for Generator.
Random seed used to initialize the pseudo-random number generator or an instantized BitGenerator. If an integer or array, used as a seed for the MT19937 BitGenerator. Values can be any integer between 0 and 2**32 - 1 inclusive, an array (or other sequence) of such integers, or None (the default). If seed is None, then the MT19937 BitGenerator is initialized by reading data from /dev/urandom (or the Windows analogue) if available or seed from the clock otherwise.
See also
The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator with a number of methods that are similar to the ones available in RandomState. RandomState, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.
get_state()
Return a tuple representing the internal state of the generator.
set_state(state)
Set the internal state of the generator from a tuple.
seed(self[, seed])
Reseed a legacy MT19937 BitGenerator
rand(d0, d1, ..., dn)
Random values in a given shape.
randn(d0, d1, ..., dn)
Return a sample (or samples) from the "standard normal" distribution.
randint(low[, high, size, dtype])
Return random integers from low (inclusive) to high (exclusive).
random_integers(low[, high, size])
Random integers of type np.int_ between low and high, inclusive.
random_sample([size])
Return random floats in the half-open interval [0.0, 1.0).
choice(a[, size, replace, p])
Generates a random sample from a given 1-D array
bytes(length)
Return random bytes.
shuffle(x)
Modify a sequence in-place by shuffling its contents.
permutation(x)
Randomly permute a sequence, or return a permuted range.
beta(a, b[, size])
Draw samples from a Beta distribution.
binomial(n, p[, size])
Draw samples from a binomial distribution.
chisquare(df[, size])
Draw samples from a chi-square distribution.
dirichlet(alpha[, size])
Draw samples from the Dirichlet distribution.
exponential([scale, size])
Draw samples from an exponential distribution.
f(dfnum, dfden[, size])
Draw samples from an F distribution.
gamma(shape[, scale, size])
Draw samples from a Gamma distribution.
geometric(p[, size])
Draw samples from the geometric distribution.
gumbel([loc, scale, size])
Draw samples from a Gumbel distribution.
hypergeometric(ngood, nbad, nsample[, size])
Draw samples from a Hypergeometric distribution.
laplace([loc, scale, size])
Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
logistic([loc, scale, size])
Draw samples from a logistic distribution.
lognormal([mean, sigma, size])
Draw samples from a log-normal distribution.
logseries(p[, size])
Draw samples from a logarithmic series distribution.
multinomial(n, pvals[, size])
Draw samples from a multinomial distribution.
multivariate_normal(mean, cov[, size, ...])
Draw random samples from a multivariate normal distribution.
negative_binomial(n, p[, size])
Draw samples from a negative binomial distribution.
noncentral_chisquare(df, nonc[, size])
Draw samples from a noncentral chi-square distribution.
noncentral_f(dfnum, dfden, nonc[, size])
Draw samples from the noncentral F distribution.
normal([loc, scale, size])
Draw random samples from a normal (Gaussian) distribution.
pareto(a[, size])
Draw samples from a Pareto II or Lomax distribution with specified shape.
poisson([lam, size])
Draw samples from a Poisson distribution.
power(a[, size])
Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
rayleigh([scale, size])
Draw samples from a Rayleigh distribution.
standard_cauchy([size])
Draw samples from a standard Cauchy distribution with mode = 0.
standard_exponential([size])
Draw samples from the standard exponential distribution.
standard_gamma(shape[, size])
Draw samples from a standard Gamma distribution.
standard_normal([size])
Draw samples from a standard Normal distribution (mean=0, stdev=1).
standard_t(df[, size])
Draw samples from a standard Student's t distribution with df degrees of freedom.
triangular(left, mode, right[, size])
Draw samples from the triangular distribution over the interval [left, right].
uniform([low, high, size])
Draw samples from a uniform distribution.
vonmises(mu, kappa[, size])
Draw samples from a von Mises distribution.
wald(mean, scale[, size])
Draw samples from a Wald, or inverse Gaussian, distribution.
weibull(a[, size])
Draw samples from a Weibull distribution.
zipf(a[, size])
Draw samples from a Zipf distribution.
Many of the RandomState methods above are exported as functions in numpy.random This usage is discouraged, as it is implemented via a global RandomState instance which is not advised on two counts:
For backward compatible legacy reasons, we cannot change this. See Quick Start.
beta(a, b[, size])
Draw samples from a Beta distribution.
binomial(n, p[, size])
Draw samples from a binomial distribution.
bytes(length)
Return random bytes.
chisquare(df[, size])
Draw samples from a chi-square distribution.
choice(a[, size, replace, p])
Generates a random sample from a given 1-D array
dirichlet(alpha[, size])
Draw samples from the Dirichlet distribution.
exponential([scale, size])
Draw samples from an exponential distribution.
f(dfnum, dfden[, size])
Draw samples from an F distribution.
gamma(shape[, scale, size])
Draw samples from a Gamma distribution.
geometric(p[, size])
Draw samples from the geometric distribution.
get_state()
Return a tuple representing the internal state of the generator.
gumbel([loc, scale, size])
Draw samples from a Gumbel distribution.
hypergeometric(ngood, nbad, nsample[, size])
Draw samples from a Hypergeometric distribution.
laplace([loc, scale, size])
Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay).
logistic([loc, scale, size])
Draw samples from a logistic distribution.
lognormal([mean, sigma, size])
Draw samples from a log-normal distribution.
logseries(p[, size])
Draw samples from a logarithmic series distribution.
multinomial(n, pvals[, size])
Draw samples from a multinomial distribution.
multivariate_normal(mean, cov[, size, ...])
Draw random samples from a multivariate normal distribution.
negative_binomial(n, p[, size])
Draw samples from a negative binomial distribution.
noncentral_chisquare(df, nonc[, size])
Draw samples from a noncentral chi-square distribution.
noncentral_f(dfnum, dfden, nonc[, size])
Draw samples from the noncentral F distribution.
normal([loc, scale, size])
Draw random samples from a normal (Gaussian) distribution.
pareto(a[, size])
Draw samples from a Pareto II or Lomax distribution with specified shape.
permutation(x)
Randomly permute a sequence, or return a permuted range.
poisson([lam, size])
Draw samples from a Poisson distribution.
power(a[, size])
Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
rand(d0, d1, ..., dn)
Random values in a given shape.
randint(low[, high, size, dtype])
Return random integers from low (inclusive) to high (exclusive).
randn(d0, d1, ..., dn)
Return a sample (or samples) from the "standard normal" distribution.
random([size])
Return random floats in the half-open interval [0.0, 1.0).
random_integers(low[, high, size])
Random integers of type np.int_ between low and high, inclusive.
random_sample([size])
Return random floats in the half-open interval [0.0, 1.0).
ranf
This is an alias of random_sample.
rayleigh([scale, size])
Draw samples from a Rayleigh distribution.
sample
This is an alias of random_sample.
seed(self[, seed])
Reseed a legacy MT19937 BitGenerator
set_state(state)
Set the internal state of the generator from a tuple.
shuffle(x)
Modify a sequence in-place by shuffling its contents.
standard_cauchy([size])
Draw samples from a standard Cauchy distribution with mode = 0.
standard_exponential([size])
Draw samples from the standard exponential distribution.
standard_gamma(shape[, size])
Draw samples from a standard Gamma distribution.
standard_normal([size])
Draw samples from a standard Normal distribution (mean=0, stdev=1).
standard_t(df[, size])
Draw samples from a standard Student's t distribution with df degrees of freedom.
triangular(left, mode, right[, size])
Draw samples from the triangular distribution over the interval [left, right].
uniform([low, high, size])
Draw samples from a uniform distribution.
vonmises(mu, kappa[, size])
Draw samples from a von Mises distribution.
wald(mean, scale[, size])
Draw samples from a Wald, or inverse Gaussian, distribution.
weibull(a[, size])
Draw samples from a Weibull distribution.
zipf(a[, size])
Draw samples from a Zipf distribution.


SeedSequence mixes sources of entropy in a reproducible way to set the initial state for independent and very probably non-overlapping BitGenerators.
Once the SeedSequence is instantiated, you can call the generate_state method to get an appropriately sized seed. Calling spawn(n) will create n SeedSequences that can be used to seed independent BitGenerators, i.e. for different threads.
The entropy for creating a SeedSequence.
A third source of entropy, used internally when calling SeedSequence.spawn
Size of the pooled entropy to store. Default is 4 to give a 128-bit entropy pool. 8 (for 256 bits) is another reasonable choice if working with larger PRNGs, but there is very little to be gained by selecting another value.
The number of children already spawned. Only pass this if reconstructing a SeedSequence from a serialized form.
Best practice for achieving reproducible bit streams is to use the default None for the initial entropy, and then use SeedSequence.entropy to log/pickle the entropy for reproducibility:
generate_state(n_words[, dtype])
Return the requested number of words for PRNG seeding.
spawn(n_children)
Spawn a number of child SeedSequence s by extending the spawn_key.


BitGenerator for Chris Doty-Humphrey’s Small Fast Chaotic PRNG.
A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance.
SFC64 is a 256-bit implementation of Chris Doty-Humphrey’s Small Fast Chaotic PRNG ([1]). SFC64 has a few different cycles that one might be on, depending on the seed; the expected period will be about \(2^{255}\) ([2]). SFC64 incorporates a 64-bit counter which means that the absolute minimum cycle length is \(2^{64}\) and that distinct seeds will not run into each other for at least \(2^{64}\) iterations.
SFC64 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access.
State and Seeding
The SFC64 state vector consists of 4 unsigned 64-bit values. The last is a 64-bit counter that increments by 1 each iteration.
The input seed is processed by SeedSequence to generate the first 3 values, then the SFC64 algorithm is iterated a small number of times to mix.
Compatibility Guarantee
SFC64 makes a guarantee that a fixed seed will always produce the same random integer stream.
“PractRand”
“Random Invertible Mapping Statistics”
state
Get or set the PRNG state
cffi
CFFI interface
ctypes
ctypes interface


Issued by polyfit when the Vandermonde matrix is rank deficient.
For more information, a way to suppress the warning, and an example of RankWarning being issued, see polyfit.


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)
Input array. The elements in a are read in the order specified by order, and packed as a 1-D array.
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.
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
1-D iterator over an array.
1-D array copy of the elements of an array in row-major order.
Change the shape of an array without changing its data.
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.
It is equivalent to reshape(-1, order=order).
When order is ‘A’, it will preserve the array’s ‘C’ or ‘F’ ordering:
When order is ‘K’, it will preserve orderings that are neither ‘C’ nor ‘F’, but won’t reverse axes:


Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.
A tuple of integer arrays, one array for each dimension.
The shape of array into which the indices from multi_index apply.
Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index.
In ‘clip’ mode, a negative index which would normally wrap will clip to 0 instead.
Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.
An array of indices into the flattened version of an array of dimensions dims.
See also
New in version 1.6.0.


Return the real part of the complex argument.
Input array.
The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.
See also


If input is complex with all imaginary parts close to zero, return real parts.
“Close to zero” is defined as tol * (machine epsilon of the type for a).
Input array.
Tolerance in machine epsilons for the complex part of the elements in the array.
If a is real, the type of a is used for the output. If a has complex elements, the returned type is float.
See also
Machine epsilon varies from machine to machine and between data types but Python floats on most platforms have a machine epsilon equal to 2.2204460492503131e-16. You can use ‘np.finfo(float).eps’ to print out the machine epsilon for floats.


Construct an ndarray that allows field access using attributes.
Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is [(x, int), (y, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['x'] and arr['y']. Record arrays allow the fields to be accessed as members of the array, using arr.x and arr.y.
Shape of output array.
The desired data-type. By default, the data-type is determined from formats, names, titles, aligned and byteorder.
A list containing the data-types for the different columns, e.g. ['i4', 'f8', 'i4']. formats does not support the new convention of using types directly, i.e. (int, float, int). Note that formats must be a list, not a tuple. Given that formats is somewhat limited, we recommend specifying dtype instead.
The name of each column, e.g. ('x', 'y', 'z').
By default, a new array is created of the given shape and data-type. If buf is specified and is an object exposing the buffer interface, the array will use the memory from the existing buffer. In this case, the offset and strides keywords are available.
Empty array of the given shape and type.
Aliases for column names. For example, if names were ('x', 'y', 'z') and titles is ('x_coordinate', 'y_coordinate', 'z_coordinate'), then arr['x'] is equivalent to both arr.x and arr.x_coordinate.
Byte-order for all fields.
Align the fields in memory as the C-compiler would.
Buffer (buf) is interpreted according to these strides (strides define how many bytes each array element, row, column, etc. occupy in memory).
Start reading buffer (buf) from this offset onwards.
Row-major (C-style) or column-major (Fortran-style) order.
See also
Construct a record array from data.
fundamental data-type for recarray.
determine a data-type from formats, names, titles.
This constructor can be compared to empty: it creates a new record array but does not fill it with data. To create a record array from data, use one of the following methods:
Create an array with two fields, x and y:
View the array as a record array:
Create a new, empty record array:
The transposed array.
Base object if memory is from some other object.
An object to simplify the interaction of the array with the ctypes module.
Python buffer object pointing to the start of the array’s data.
Data-type of the array’s elements.
Information about the memory layout of the array.
A 1-D iterator over the array.
The imaginary part of the array.
Length of one array element in bytes.
Total bytes consumed by the elements of the array.
Number of array dimensions.
The real part of the array.
Tuple of array dimensions.
Number of elements in the array.
Tuple of bytes to step in each dimension when traversing an array.
all([axis, out, keepdims, where])
Returns True if all elements evaluate to True.
any([axis, out, keepdims, where])
Returns True if any of the elements of a evaluate to True.
argmax([axis, out])
Return indices of the maximum values along the given axis.
argmin([axis, out])
Return indices of the minimum values along the given axis.
argpartition(kth[, axis, kind, order])
Returns the indices that would partition this array.
argsort([axis, kind, order])
Returns the indices that would sort this array.
astype(dtype[, order, casting, subok, copy])
Copy of the array, cast to a specified type.
byteswap([inplace])
Swap the bytes of the array elements
choose(choices[, out, mode])
Use an index array to construct a new array from a set of choices.
clip([min, max, out])
Return an array whose values are limited to [min, max].
compress(condition[, axis, out])
Return selected slices of this array along given axis.
conj()
Complex-conjugate all elements.
conjugate()
Return the complex conjugate, element-wise.
copy([order])
Return a copy of the array.
cumprod([axis, dtype, out])
Return the cumulative product of the elements along the given axis.
cumsum([axis, dtype, out])
Return the cumulative sum of the elements along the given axis.
diagonal([offset, axis1, axis2])
Return specified diagonals.
dump(file)
Dump a pickle of the array to the specified file.
dumps()
Returns the pickle of the array as a string.
fill(value)
Fill the array with a scalar value.
flatten([order])
Return a copy of the array collapsed into one dimension.
getfield(dtype[, offset])
Returns a field of the given array as a certain type.
item(*args)
Copy an element of an array to a standard Python scalar and return it.
itemset(*args)
Insert scalar into an array (scalar is cast to array's dtype, if possible)
max([axis, out, keepdims, initial, where])
Return the maximum along a given axis.
mean([axis, dtype, out, keepdims, where])
Returns the average of the array elements along given axis.
min([axis, out, keepdims, initial, where])
Return the minimum along a given axis.
newbyteorder([new_order])
Return the array with the same data viewed with a different byte order.
nonzero()
Return the indices of the elements that are non-zero.
partition(kth[, axis, kind, order])
Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.
prod([axis, dtype, out, keepdims, initial, ...])
Return the product of the array elements over the given axis
ptp([axis, out, keepdims])
Peak to peak (maximum - minimum) value along a given axis.
put(indices, values[, mode])
Set a.flat[n] = values[n] for all n in indices.
ravel([order])
Return a flattened array.
repeat(repeats[, axis])
Repeat elements of an array.
reshape(shape[, order])
Returns an array containing the same data with a new shape.
resize(new_shape[, refcheck])
Change shape and size of array in-place.
round([decimals, out])
Return a with each element rounded to the given number of decimals.
searchsorted(v[, side, sorter])
Find indices where elements of v should be inserted in a to maintain order.
setfield(val, dtype[, offset])
Put a value into a specified place in a field defined by a data-type.
setflags([write, align, uic])
Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
sort([axis, kind, order])
Sort an array in-place.
squeeze([axis])
Remove axes of length one from a.
std([axis, dtype, out, ddof, keepdims, where])
Returns the standard deviation of the array elements along given axis.
sum([axis, dtype, out, keepdims, initial, where])
Return the sum of the array elements over the given axis.
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
take(indices[, axis, out, mode])
Return an array formed from the elements of a at the given indices.
tobytes([order])
Construct Python bytes containing the raw data bytes in the array.
tofile(fid[, sep, format])
Write array to a file as text or binary (default).
tolist()
Return the array as an a.ndim-levels deep nested list of Python scalars.
tostring([order])
A compatibility alias for tobytes, with exactly the same behavior.
trace([offset, axis1, axis2, dtype, out])
Return the sum along diagonals of the array.
transpose(*axes)
Returns a view of the array with axes transposed.
var([axis, dtype, out, ddof, keepdims, where])
Returns the variance of the array elements, along given axis.
view([dtype][, type])
New view of array with the same data.
dot
field


Return the reciprocal of the argument, element-wise.
Calculates 1/x.
Input array.
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.
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.
For other keyword-only arguments, see the ufunc docs.
Return array. This is a scalar if x is a scalar.
Note
This function is not designed to work with integers.
For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow.


A data-type scalar that allows field access as attribute lookup.
Scalar attribute identical to the corresponding array attribute.
base object
Pointer to start of data.
dtype object
integer value of flags
A 1-D view of the scalar.
The imaginary part of the scalar.
The length of one element in bytes.
The length of the scalar in bytes.
The number of array dimensions.
The real part of the scalar.
Tuple of array dimensions.
The number of elements in the gentype.
Tuple of bytes steps in each dimension.
all
Scalar method identical to the corresponding array attribute.
any
Scalar method identical to the corresponding array attribute.
argmax
Scalar method identical to the corresponding array attribute.
argmin
Scalar method identical to the corresponding array attribute.
argsort
Scalar method identical to the corresponding array attribute.
astype
Scalar method identical to the corresponding array attribute.
byteswap
Scalar method identical to the corresponding array attribute.
choose
Scalar method identical to the corresponding array attribute.
clip
Scalar method identical to the corresponding array attribute.
compress
Scalar method identical to the corresponding array attribute.
conjugate
Scalar method identical to the corresponding array attribute.
copy
Scalar method identical to the corresponding array attribute.
cumprod
Scalar method identical to the corresponding array attribute.
cumsum
Scalar method identical to the corresponding array attribute.
diagonal
Scalar method identical to the corresponding array attribute.
dump
Scalar method identical to the corresponding array attribute.
dumps
Scalar method identical to the corresponding array attribute.
fill
Scalar method identical to the corresponding array attribute.
flatten
Scalar method identical to the corresponding array attribute.
getfield
Scalar method identical to the corresponding array attribute.
item
Scalar method identical to the corresponding array attribute.
itemset
Scalar method identical to the corresponding array attribute.
max
Scalar method identical to the corresponding array attribute.
mean
Scalar method identical to the corresponding array attribute.
min
Scalar method identical to the corresponding array attribute.
newbyteorder([new_order])
Return a new dtype with a different byte order.
nonzero
Scalar method identical to the corresponding array attribute.
pprint()
Pretty-print all fields.
prod
Scalar method identical to the corresponding array attribute.
ptp
Scalar method identical to the corresponding array attribute.
put
Scalar method identical to the corresponding array attribute.
ravel
Scalar method identical to the corresponding array attribute.
repeat
Scalar method identical to the corresponding array attribute.
reshape
Scalar method identical to the corresponding array attribute.
resize
Scalar method identical to the corresponding array attribute.
round
Scalar method identical to the corresponding array attribute.
searchsorted
Scalar method identical to the corresponding array attribute.
setfield
Scalar method identical to the corresponding array attribute.
setflags
Scalar method identical to the corresponding array attribute.
sort
Scalar method identical to the corresponding array attribute.
squeeze
Scalar method identical to the corresponding array attribute.
std
Scalar method identical to the corresponding array attribute.
sum
Scalar method identical to the corresponding array attribute.
swapaxes
Scalar method identical to the corresponding array attribute.
take
Scalar method identical to the corresponding array attribute.
tofile
Scalar method identical to the corresponding array attribute.
tolist
Scalar method identical to the corresponding array attribute.
tostring
Scalar method identical to the corresponding array attribute.
trace
Scalar method identical to the corresponding array attribute.
transpose
Scalar method identical to the corresponding array attribute.
var
Scalar method identical to the corresponding array attribute.
view
Scalar method identical to the corresponding array attribute.
conj
tobytes


Returns the element-wise remainder of division.
Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operator``x1 % x2`` and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod.
Warning
This should not be confused with:
Dividend array.
Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
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.
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.
For other keyword-only arguments, see the ufunc docs.
The element-wise remainder of the quotient floor_divide(x1, x2). This is a scalar if both x1 and x2 are scalars.
See also
Equivalent of Python // operator.
Simultaneous floor division and remainder.
Equivalent of the MATLAB rem function.
Returns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers. mod is an alias of remainder.
The % operator can be used as a shorthand for np.remainder on ndarrays.


Repeat elements of an array.
Input array.
The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.
The axis along which to repeat values. By default, use the flattened input array, and return a flat output array.
Output array which has the same shape as a, except along the given axis.
See also
Tile an array.
Find the unique elements of an array.


Return an ndarray of the provided type that satisfies requirements.
This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes).
The object to be converted to a type-and-requirement-satisfying array.
The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification.
The requirements list can be any of the following
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.
Array with specified requirements and type if given.
See also
Convert input to an ndarray.
Convert to an ndarray, but pass through ndarray subclasses.
Convert input to a contiguous array.
Convert input to an ndarray with column-major memory order.
Information about the memory layout of the array.
The returned array will be guaranteed to have the listed requirements by making a copy if needed.


Gives a new shape to an array without changing its data.
Array to be reshaped.
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.
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.
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
Equivalent method.
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:
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:
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.


Return a new array with the specified shape.
If the new array is larger than the original array, then the new array is filled with repeated copies of a. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.
Array to be resized.
Shape of resized array.
The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order.
See also
Reshape an array without changing the total size.
Enlarge and pad an array.
Repeat elements of an array.
resize an array in-place.
When the total size of the array does not change reshape should be used. In most other cases either indexing (to reduce the size) or padding (to increase the size) may be a more appropriate solution.
Warning: This functionality does not consider axes separately, i.e. it does not apply interpolation/extrapolation. It fills the return array with the required number of elements, iterating over a in C-order, disregarding axes (and cycling back from the start if the new shape is larger). This functionality is therefore not suitable to resize images, or data where each axis represents a separate and distinct entity.


Returns the type that results from applying the NumPy type promotion rules to the arguments.
Type promotion in NumPy works similarly to the rules in languages like C++, with some slight differences. When both scalars and arrays are used, the array’s type takes precedence and the actual value of the scalar is taken into account.
For example, calculating 3*a, where a is an array of 32-bit floats, intuitively should result in a 32-bit float output. If the 3 is a 32-bit integer, the NumPy rules indicate it can’t convert losslessly into a 32-bit float, so a 64-bit float should be the result type. By examining the value of the constant, ‘3’, we see that it fits in an 8-bit integer, which can be cast losslessly into the 32-bit float.
The operands of some operation whose result type is needed.
The result type.
See also
New in version 1.6.0.
The specific algorithm used is as follows.
Categories are determined by first checking which of boolean, integer (int/uint), or floating point (float/complex) the maximum kind of all the arrays and the scalars are.
If there are only scalars or the maximum category of the scalars is higher than the maximum category of the arrays, the data types are combined with promote_types to produce the return value.
Otherwise, min_scalar_type is called on each array, and the resulting data types are all combined with promote_types to produce the return value.
The set of int values is not a subset of the uint values for types with the same number of bits, something not reflected in min_scalar_type, but handled as a special case in result_type.


Shift the bits of an integer to the right.
Bits are shifted to the right x2. Because the internal representation of numbers is in binary format, this operation is equivalent to dividing x1 by 2**x2.
Input values.
Number of bits to remove at the right of x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
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.
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.
For other keyword-only arguments, see the ufunc docs.
Return x1 with bits shifted x2 times to the right. This is a scalar if both x1 and x2 are scalars.
See also
Shift the bits of an integer to the left.
Return the binary representation of the input number as a string.
The >> operator can be used as a shorthand for np.right_shift on ndarrays.


Round elements of the array to the nearest integer.
Input array.
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.
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.
For other keyword-only arguments, see the ufunc docs.
Output array is same shape and type as x. This is a scalar if x is a scalar.
See also
For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc.


Roll array elements along a given axis.
Elements that roll beyond the last position are re-introduced at the first.
Input array.
The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while axis is a tuple of ints, then the same value is used for all given axes.
Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.
Output array, with the same shape as a.
See also
Roll the specified axis backwards, until it lies in a given position.
New in version 1.12.0.
Supports rolling over multiple dimensions simultaneously.


Roll the specified axis backwards, until it lies in a given position.
This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11.
Input array.
The axis to be rolled. The positions of the other axes do not change relative to one another.
When start <= axis, the axis is rolled back until it lies in this position. When start > axis, the axis is rolled until it lies before this position. The default, 0, results in a “complete” roll. The following table describes how negative values of start are interpreted:
start
Normalized start
-(arr.ndim+1)
raise AxisError
-arr.ndim
0
⋮
⋮
-1
arr.ndim-1
0
0
⋮
⋮
arr.ndim
arr.ndim
arr.ndim + 1
raise AxisError
For NumPy >= 1.10.0 a view of a is always returned. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned.
See also
Move array axes to new positions.
Roll the elements of an array by a number of positions along a given axis.


Return the roots of a polynomial with coefficients given in p.
Note
This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.
The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by:
Rank-1 array of polynomial coefficients.
An array containing the roots of the polynomial.
When p cannot be converted to a rank-1 array.
See also
Find the coefficients of a polynomial with a given sequence of roots.
Compute polynomial values.
Least squares polynomial fit.
A one-dimensional polynomial class.
The algorithm relies on computing the eigenvalues of the companion matrix [1].
R. A. Horn & C. R. Johnson, Matrix Analysis. Cambridge, UK: Cambridge University Press, 1999, pp. 146-7.


Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis.
Array of two or more dimensions.
Number of times the array is rotated by 90 degrees.
The array is rotated in the plane defined by the axes. Axes must be different.
New in version 1.12.0.
A rotated view of m.
See also
Reverse the order of elements in an array along the given axis.
Flip an array horizontally.
Flip an array vertically.
rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))
rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))


Round an array to the given number of decimals.
See also
equivalent function; see for details.


Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.
This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.
The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.
The array formed by stacking the given arrays, will be at least 2-D.
See also
Join a sequence of arrays along an existing axis.
Join a sequence of arrays along a new axis.
Assemble an nd-array from nested lists of blocks.
Stack arrays in sequence horizontally (column wise).
Stack arrays in sequence depth wise (along third axis).
Stack 1-D arrays as columns into a 2-D array.
Split an array into multiple sub-arrays vertically (row-wise).


A nicer way to build up index tuples for arrays.
Note
Use one of the two predefined instances index_exp or s_ rather than directly using IndexExpression.
For any index combination, including slicing and axis insertion, a[indices] is the same as a[np.index_exp[indices]] for any array a. However, np.index_exp[indices] can be used anywhere in Python code and returns a tuple of slice objects that can be used in the construction of complex index expressions.
If True, always returns a tuple.
See also
Predefined instance that always returns a tuple: index_exp = IndexExpression(maketuple=True).
Predefined instance without tuple conversion: s_ = IndexExpression(maketuple=False).
You can do all this with slice() plus a few special objects, but there’s a lot to remember and this version is simpler because it uses the standard array indexing syntax.


Save an array to a binary file in NumPy .npy format.
File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one.
Array data to be saved.
Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations, for example if the stored objects require libraries that are not available, and not all pickled data is compatible between Python 2 and Python 3). Default: True
Only useful in forcing objects in object arrays on Python 3 to be pickled in a Python 2 compatible way. If fix_imports is True, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2.
See also
Save several arrays into a .npz archive
For a description of the .npy format, see numpy.lib.format.
Any data saved to the file is appended to the end of the file.


Save an array to a text file.
If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently.
Data to be saved to a text file.
A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case delimiter is ignored. For complex X, the legal options for fmt are:
String or character separating columns.
String or character separating lines.
New in version 1.5.0.
String that will be written at the beginning of the file.
New in version 1.7.0.
String that will be written at the end of the file.
New in version 1.7.0.
String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt.
New in version 1.7.0.
Encoding used to encode the outputfile. Does not apply to output streams. If the encoding is something other than ‘bytes’ or ‘latin1’ you will not be able to load the file in NumPy versions < 1.14. Default is ‘latin1’.
New in version 1.14.0.
See also
Save an array to a binary file in NumPy .npy format
Save several arrays into an uncompressed .npz archive
Save several arrays into a compressed .npz archive
Further explanation of the fmt parameter (%[flag]width[.precision]specifier):
- : left justify
+ : Forces to precede result with + or -.
0 : Left pad the number with zeros instead of space (see width).
Minimum number of characters to be printed. The value is not truncated if it has more characters.
c : character
d or i : signed decimal integer
e or E : scientific notation with e or E.
f : decimal floating point
g,G : use the shorter of e,E or f
o : signed octal
s : string of characters
u : unsigned decimal integer
x,X : unsigned hexadecimal integer
This explanation of fmt is not complete, for an exhaustive specification see [1].
Format Specification Mini-Language, Python Documentation.


Save several arrays into a single file in uncompressed .npz format.
Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y).
If arrays are specified as positional arguments, i.e., savez(fn,
x, y), their names will be arr_0, arr_1, etc.
Either the filename (string) or an open file (file-like object) where the data will be saved. If file is a string or a Path, the .npz extension will be appended to the filename if it is not already there.
Arrays to save to the file. Please use keyword arguments (see kwds below) to assign names to arrays. Arrays specified as args will be named “arr_0”, “arr_1”, and so on.
Arrays to save to the file. Each array will be saved to the output file with its corresponding keyword name.
See also
Save a single array to a binary file in NumPy format.
Save an array to a file as plain text.
Save several arrays into a compressed .npz archive
The .npz file format is a zipped archive of files named after the variables they contain. The archive is not compressed and each file in the archive contains one variable in .npy format. For a description of the .npy format, see numpy.lib.format.
When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves.
Keys passed in kwds are used as filenames inside the ZIP archive. Therefore, keys should be valid filenames; e.g., avoid keys that begin with / or contain ..
When naming variables with keyword arguments, it is not possible to name a variable file, as this would cause the file argument to be defined twice in the call to savez.
Using savez with *args, the arrays are saved with default names.
Using savez with **kwds, the arrays are saved with the keyword names.


Save several arrays into a single file in compressed .npz format.
Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y).
If arrays are specified as positional arguments, i.e., savez(fn,
x, y), their names will be arr_0, arr_1, etc.
Either the filename (string) or an open file (file-like object) where the data will be saved. If file is a string or a Path, the .npz extension will be appended to the filename if it is not already there.
Arrays to save to the file. Please use keyword arguments (see kwds below) to assign names to arrays. Arrays specified as args will be named “arr_0”, “arr_1”, and so on.
Arrays to save to the file. Each array will be saved to the output file with its corresponding keyword name.
See also
Save a single array to a binary file in NumPy format.
Save an array to a file as plain text.
Save several arrays into an uncompressed .npz file format
Load the files created by savez_compressed.
The .npz file format is a zipped archive of files named after the variables they contain. The archive is compressed with zipfile.ZIP_DEFLATED and each file in the archive contains one variable in .npy format. For a description of the .npy format, see numpy.lib.format.
When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves.


Return the string representation of a scalar dtype.
If a scalar dtype, the corresponding string character is returned. If an object, sctype2char tries to infer its scalar type and then return the corresponding string character.
The string character corresponding to the scalar type.
If sctype is an object for which the type can not be inferred.
See also


Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.
Assuming that a is sorted:
side
returned index i satisfies
left
a[i-1] < v <= a[i]
right
a[i-1] <= v < a[i]
Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.
Values to insert into a.
If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).
Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.
New in version 1.7.0.
Array of insertion points with the same shape as v, or an integer if v is a scalar.
See also
Return a sorted copy of an array.
Produce histogram from 1-D data.
Binary search is used to find the required insertion points.
As of NumPy 1.4.0 searchsorted works with real/complex arrays containing nan values. The enhanced sort order is documented in sort.
This function uses the same algorithm as the builtin python bisect.bisect_left (side='left') and bisect.bisect_right (side='right') functions, which is also vectorized in the v argument.


Return an array drawn from elements in choicelist, depending on conditions.
The list of conditions which determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used.
The list of arrays from which the output elements are taken. It has to be of the same length as condlist.
The element inserted in output when all conditions evaluate to False.
The output at position m is the m-th element of the array in choicelist where the m-th element of the corresponding array in condlist is True.
See also
Return elements from one of two arrays depending on condition.