numpy.nanpercentile   numpy.nanpercentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=<no value>, *, interpolation=None)[source]

Compute the qth percentile of the data along the specified axis, while ignoring nan values. Returns the qth percentile(s) of the array elements.  New in version 1.9.0.   Parameters

aarray_like

Input array or object that can be converted to an array, containing nan values to be ignored.
qarray_like of float

Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive.
axis{int, tuple of int, None}, optional

Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array.
outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.
overwrite_inputbool, optional

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

This parameter specifies the method to use for estimating the percentile. 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:  ‘inverted_cdf’ ‘averaged_inverted_cdf’ ‘closest_observation’ ‘interpolated_inverted_cdf’ ‘hazen’ ‘weibull’ ‘linear’ (default) ‘median_unbiased’ ‘normal_unbiased’  The first three methods are discontiuous. NumPy further defines the following discontinuous variations of the default ‘linear’ (7.) option:  ‘lower’ ‘higher’, ‘midpoint’ ‘nearest’   Changed in version 1.22.0: This argument was previously called “interpolation” and only offered the “linear” default and last four options.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a. If this is anything but the default value it will be passed through (in the special case of an empty array) to the mean function of the underlying array. If the array is a sub-class and mean does not have the kwarg keepdims this will raise a RuntimeError.
interpolationstr, optional

Deprecated name for the method keyword argument.  Deprecated since version 1.22.0.     Returns

percentilescalar or ndarray

If q is a single percentile and axis=None, then the result is a scalar. If multiple percentiles are given, first axis of the result corresponds to the percentiles. 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  nanmean
nanmedian

equivalent to nanpercentile(..., 50)
percentile, median, mean

nanquantile

equivalent to nanpercentile, except q in range [0, 1].    Notes For more information please see numpy.percentile References  1
R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages,” The American Statistician, 50(4), pp. 361-365, 1996   Examples >>> a = np.array([[10., 7., 4.], [3., 2., 1.]])
>>> a[0][1] = np.nan
>>> a
array([[10.,  nan,   4.],
      [ 3.,   2.,   1.]])
>>> np.percentile(a, 50)
nan
>>> np.nanpercentile(a, 50)
3.0
>>> np.nanpercentile(a, 50, axis=0)
array([6.5, 2. , 2.5])
>>> np.nanpercentile(a, 50, axis=1, keepdims=True)
array([[7.],
       [2.]])
>>> m = np.nanpercentile(a, 50, axis=0)
>>> out = np.zeros_like(m)
>>> np.nanpercentile(a, 50, axis=0, out=out)
array([6.5, 2. , 2.5])
>>> m
array([6.5,  2. ,  2.5])
 >>> b = a.copy()
>>> np.nanpercentile(b, 50, axis=1, overwrite_input=True)
array([7., 2.])
>>> assert not np.all(a==b)


numpy.nanprod   numpy.nanprod(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]

Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones. One is returned for slices that are all-NaN or empty.  New in version 1.10.0.   Parameters

aarray_like

Array containing numbers whose product is desired. If a is not an array, a conversion is attempted.
axis{int, tuple of int, None}, optional

Axis or axes along which the product is computed. The default is to compute the product of the flattened array.
dtypedata-type, optional

The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact.
outndarray, optional

Alternate output array in which to place the result. The default is None. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details. The casting of NaN to integer can yield unexpected results.
keepdimsbool, optional

If 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 arr.
initialscalar, optional

The starting value for this product. See reduce for details.  New in version 1.22.0.
wherearray_like of bool, optional

Elements to include in the product. See reduce for details.  New in version 1.22.0.     Returns

nanprodndarray

A new array holding the result is returned unless out is specified, in which case it is returned.      See also  numpy.prod

Product across array propagating NaNs.  isnan

Show which elements are NaN.    Examples >>> np.nanprod(1)
1
>>> np.nanprod([1])
1
>>> np.nanprod([1, np.nan])
1.0
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanprod(a)
6.0
>>> np.nanprod(a, axis=0)
array([3., 2.])


numpy.nanquantile   numpy.nanquantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=<no value>, *, interpolation=None)[source]

Compute the qth quantile of the data along the specified axis, while ignoring nan values. Returns the qth quantile(s) of the array elements.  New in version 1.15.0.   Parameters

aarray_like

Input array or object that can be converted to an array, containing nan values to be ignored
qarray_like of float

Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.
axis{int, tuple of int, None}, optional

Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.
outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.
overwrite_inputbool, optional

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

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:  ‘inverted_cdf’ ‘averaged_inverted_cdf’ ‘closest_observation’ ‘interpolated_inverted_cdf’ ‘hazen’ ‘weibull’ ‘linear’ (default) ‘median_unbiased’ ‘normal_unbiased’  The first three methods are discontiuous. NumPy further defines the following discontinuous variations of the default ‘linear’ (7.) option:  ‘lower’ ‘higher’, ‘midpoint’ ‘nearest’   Changed in version 1.22.0: This argument was previously called “interpolation” and only offered the “linear” default and last four options.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a. If this is anything but the default value it will be passed through (in the special case of an empty array) to the mean function of the underlying array. If the array is a sub-class and mean does not have the kwarg keepdims this will raise a RuntimeError.
interpolationstr, optional

Deprecated name for the method keyword argument.  Deprecated since version 1.22.0.     Returns

quantilescalar or ndarray

If q is a single percentile 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  quantile

nanmean, nanmedian

nanmedian

equivalent to nanquantile(..., 0.5)  nanpercentile

same as nanquantile, but with q in the range [0, 100].    Notes For more information please see numpy.quantile References  1
R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages,” The American Statistician, 50(4), pp. 361-365, 1996   Examples >>> a = np.array([[10., 7., 4.], [3., 2., 1.]])
>>> a[0][1] = np.nan
>>> a
array([[10.,  nan,   4.],
      [ 3.,   2.,   1.]])
>>> np.quantile(a, 0.5)
nan
>>> np.nanquantile(a, 0.5)
3.0
>>> np.nanquantile(a, 0.5, axis=0)
array([6.5, 2. , 2.5])
>>> np.nanquantile(a, 0.5, axis=1, keepdims=True)
array([[7.],
       [2.]])
>>> m = np.nanquantile(a, 0.5, axis=0)
>>> out = np.zeros_like(m)
>>> np.nanquantile(a, 0.5, axis=0, out=out)
array([6.5, 2. , 2.5])
>>> m
array([6.5,  2. ,  2.5])
>>> b = a.copy()
>>> np.nanquantile(b, 0.5, axis=1, overwrite_input=True)
array([7., 2.])
>>> assert not np.all(a==b)


numpy.nanstd   numpy.nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)[source]

Compute the standard deviation along the specified axis, while ignoring NaNs. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a RuntimeWarning is raised.  New in version 1.8.0.   Parameters

aarray_like

Calculate the standard deviation of the non-NaN values.
axis{int, tuple of int, None}, optional

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.
dtypedtype, optional

Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.
outndarray, optional

Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary.
ddofint, optional

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a. If this value is anything but the default it is passed through as-is to the relevant functions of the sub-classes. If these functions do not have a keepdims kwarg, a RuntimeError will be raised.
wherearray_like of bool, optional

Elements to include in the standard deviation. See reduce for details.  New in version 1.22.0.     Returns

standard_deviationndarray, see dtype parameter above.

If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN.      See also
var, mean, std

nanvar, nanmean

Output type determination
  Notes The standard deviation is the square root of the average of the squared deviations from the mean: std = sqrt(mean(abs(x - x.mean())**2)). The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the std is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue. Examples >>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanstd(a)
1.247219128924647
>>> np.nanstd(a, axis=0)
array([1., 0.])
>>> np.nanstd(a, axis=1)
array([0.,  0.5]) # may vary


numpy.nansum   numpy.nansum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source]

Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. In NumPy versions <= 1.9.0 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned.  Parameters

aarray_like

Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.
axis{int, tuple of int, None}, optional

Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array.
dtypedata-type, optional

The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of a is used. An exception is when a has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact.  New in version 1.8.0.
outndarray, optional

Alternate output array in which to place the result. The default is None. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See Output type determination for more details. The casting of NaN to integer can yield unexpected results.  New in version 1.8.0.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a. If the value is anything but the default, then keepdims will be passed through to the mean or sum methods of sub-classes of ndarray. If the sub-classes methods does not implement keepdims any exceptions will be raised.  New in version 1.8.0.
initialscalar, optional

Starting value for the sum. See reduce for details.  New in version 1.22.0.
wherearray_like of bool, optional

Elements to include in the sum. See reduce for details.  New in version 1.22.0.     Returns

nansumndarray.

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

Sum across array propagating NaNs.  isnan

Show which elements are NaN.  isfinite

Show which elements are not NaN or +/-inf.    Notes If both positive and negative infinity are present, the sum will be Not A Number (NaN). Examples >>> np.nansum(1)
1
>>> np.nansum([1])
1
>>> np.nansum([1, np.nan])
1.0
>>> a = np.array([[1, 1], [1, np.nan]])
>>> np.nansum(a)
3.0
>>> np.nansum(a, axis=0)
array([2.,  1.])
>>> np.nansum([1, np.nan, np.inf])
inf
>>> np.nansum([1, np.nan, np.NINF])
-inf
>>> from numpy.testing import suppress_warnings
>>> with suppress_warnings() as sup:
...     sup.filter(RuntimeWarning)
...     np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present
nan


numpy.nanvar   numpy.nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)[source]

Compute the variance along the specified axis, while ignoring NaNs. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a RuntimeWarning is raised.  New in version 1.8.0.   Parameters

aarray_like

Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.
axis{int, tuple of int, None}, optional

Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.
dtypedata-type, optional

Type to use in computing the variance. For arrays of integer type the default is float64; for arrays of float types it is the same as the array type.
outndarray, optional

Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary.
ddofint, optional

“Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.
wherearray_like of bool, optional

Elements to include in the variance. See reduce for details.  New in version 1.22.0.     Returns

variancendarray, see dtype parameter above

If out is None, return a new array containing the variance, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN.      See also  std

Standard deviation  mean

Average  var

Variance while not ignoring NaNs
nanstd, nanmean

Output type determination
  Notes The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x - x.mean())**2). The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of a hypothetical infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue. For this function to work on sub-classes of ndarray, they must define sum with the kwarg keepdims Examples >>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanvar(a)
1.5555555555555554
>>> np.nanvar(a, axis=0)
array([1.,  0.])
>>> np.nanvar(a, axis=1)
array([0.,  0.25])  # may vary


numpy.ndarray   class numpy.ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)[source]

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.) Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array. For more information, refer to the numpy module and examine the methods and attributes of an array.  Parameters
 (for the __new__ method; see Notes below)

shapetuple of ints

Shape of created array.
dtypedata-type, optional

Any object that can be interpreted as a numpy data type.
bufferobject exposing buffer interface, optional

Used to fill the array with data.
offsetint, optional

Offset of array data in buffer.
stridestuple of ints, optional

Strides of data in memory.
order{‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order.      See also  array

Construct an array.  zeros

Create an array, each element of which is zero.  empty

Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).  dtype

Create a data-type.  numpy.typing.NDArray

An ndarray alias generic w.r.t. its dtype.type.    Notes There are two modes of creating an array using __new__:  If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.  No __init__ method is needed because the array is fully initialized after the __new__ method. Examples These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways of constructing an ndarray. First mode, buffer is None: >>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
       [     nan, 2.5e-323]])
 Second mode: >>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])
  Attributes

Tndarray

The transposed array.
databuffer

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

Data-type of the array’s elements.
flagsdict

Information about the memory layout of the array.
flatnumpy.flatiter object

A 1-D iterator over the array.
imagndarray

The imaginary part of the array.
realndarray

The real part of the array.
sizeint

Number of elements in the array.
itemsizeint

Length of one array element in bytes.
nbytesint

Total bytes consumed by the elements of the array.
ndimint

Number of array dimensions.
shapetuple of ints

Tuple of array dimensions.
stridestuple of ints

Tuple of bytes to step in each dimension when traversing an array.
ctypesctypes object

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

Base object if memory is from some other object.     Methods
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


numpy.ndenumerate   class numpy.ndenumerate(arr)[source]

Multidimensional index iterator. Return an iterator yielding pairs of array coordinates and values.  Parameters

arrndarray

Input array.      See also
ndindex, flatiter

  Examples >>> a = np.array([[1, 2], [3, 4]])
>>> for index, x in np.ndenumerate(a):
...     print(index, x)
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4


numpy.ndindex   class numpy.ndindex(*shape)[source]

An N-dimensional iterator object to index arrays. Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each iteration a tuple of indices is returned, the last dimension is iterated over first.  Parameters

shapeints, or a single tuple of ints

The size of each dimension of the array can be passed as individual parameters or as the elements of a tuple.      See also
ndenumerate, flatiter

  Examples Dimensions as individual arguments >>> for index in np.ndindex(3, 2, 1):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)
 Same dimensions - but in a tuple (3, 2, 1) >>> for index in np.ndindex((3, 2, 1)):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)
 Methods
ndincr() Increment the multi-dimensional index by one.


numpy.nditer   class numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0)[source]

Efficient multi-dimensional iterator object to iterate over arrays. To get started using this object, see the introductory guide to array iteration.  Parameters

opndarray or sequence of array_like

The array(s) to iterate over.
flagssequence of str, optional

Flags to control the behavior of the iterator.
buffered enables buffering when required.
c_index causes a C-order index to be tracked.
f_index causes a Fortran-order index to be tracked.
multi_index causes a multi-index, or a tuple of indices with one per iteration dimension, to be tracked.
common_dtype causes all the operands to be converted to a common data type, with copying or buffering as necessary.
copy_if_overlap causes the iterator to determine if read operands have overlap with write operands, and make temporary copies as necessary to avoid overlap. False positives (needless copying) are possible in some cases.
delay_bufalloc delays allocation of the buffers until a reset() call is made. Allows allocate operands to be initialized before their values are copied into the buffers.
external_loop causes the values given to be one-dimensional arrays with multiple values instead of zero-dimensional arrays.
grow_inner allows the value array sizes to be made larger than the buffer size when both buffered and external_loop is used.
ranged allows the iterator to be restricted to a sub-range of the iterindex values.
refs_ok enables iteration of reference types, such as object arrays.
reduce_ok enables iteration of readwrite operands which are broadcasted, also known as reduction operands.
zerosize_ok allows itersize to be zero.
op_flagslist of list of str, optional

This is a list of flags for each operand. At minimum, one of readonly, readwrite, or writeonly must be specified.
readonly indicates the operand will only be read from.
readwrite indicates the operand will be read from and written to.
writeonly indicates the operand will only be written to.
no_broadcast prevents the operand from being broadcasted.
contig forces the operand data to be contiguous.
aligned forces the operand data to be aligned.
nbo forces the operand data to be in native byte order.
copy allows a temporary read-only copy if required.
updateifcopy allows a temporary read-write copy if required.
allocate causes the array to be allocated if it is None in the op parameter.
no_subtype prevents an allocate operand from using a subtype.
arraymask indicates that this operand is the mask to use for selecting elements when writing to operands with the ‘writemasked’ flag set. The iterator does not enforce this, but when writing from a buffer back to the array, it only copies those elements indicated by this mask.
writemasked indicates that only elements where the chosen arraymask operand is True will be written to.
overlap_assume_elementwise can be used to mark operands that are accessed only in the iterator order, to allow less conservative copying when copy_if_overlap is present.
op_dtypesdtype or tuple of dtype(s), optional

The required data type(s) of the operands. If copying or buffering is enabled, the data will be converted to/from their original types.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Controls the iteration order. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. This also affects the element memory order of allocate operands, as they are allocated to be compatible with iteration order. Default is ‘K’.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Controls what kind of data casting may occur when making a copy or buffering. Setting this to ‘unsafe’ is not recommended, as it can adversely affect accumulations.  ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done.
op_axeslist of list of ints, optional

If provided, is a list of ints or None for each operands. The list of axes for an operand is a mapping from the dimensions of the iterator to the dimensions of the operand. A value of -1 can be placed for entries, causing that dimension to be treated as newaxis.
itershapetuple of ints, optional

The desired shape of the iterator. This allows allocate operands with a dimension mapped by op_axes not corresponding to a dimension of a different operand to get a value not equal to 1 for that dimension.
buffersizeint, optional

When buffering is enabled, controls the size of the temporary buffers. Set to 0 for the default value.     Notes nditer supersedes flatiter. The iterator implementation behind nditer is also exposed by the NumPy C API. The Python exposure supplies two iteration interfaces, one which follows the Python iterator protocol, and another which mirrors the C-style do-while pattern. The native Python approach is better in most cases, but if you need the coordinates or index of an iterator, use the C-style pattern. Examples Here is how we might write an iter_add function, using the Python iterator protocol: >>> def iter_add_py(x, y, out=None):
...     addop = np.add
...     it = np.nditer([x, y, out], [],
...                 [['readonly'], ['readonly'], ['writeonly','allocate']])
...     with it:
...         for (a, b, c) in it:
...             addop(a, b, out=c)
...         return it.operands[2]
 Here is the same function, but following the C-style pattern: >>> def iter_add(x, y, out=None):
...    addop = np.add
...    it = np.nditer([x, y, out], [],
...                [['readonly'], ['readonly'], ['writeonly','allocate']])
...    with it:
...        while not it.finished:
...            addop(it[0], it[1], out=it[2])
...            it.iternext()
...        return it.operands[2]
 Here is an example outer product function: >>> def outer_it(x, y, out=None):
...     mulop = np.multiply
...     it = np.nditer([x, y, out], ['external_loop'],
...             [['readonly'], ['readonly'], ['writeonly', 'allocate']],
...             op_axes=[list(range(x.ndim)) + [-1] * y.ndim,
...                      [-1] * x.ndim + list(range(y.ndim)),
...                      None])
...     with it:
...         for (a, b, c) in it:
...             mulop(a, b, out=c)
...         return it.operands[2]
 >>> a = np.arange(2)+1
>>> b = np.arange(3)+1
>>> outer_it(a,b)
array([[1, 2, 3],
       [2, 4, 6]])
 Here is an example function which operates like a “lambda” ufunc: >>> def luf(lamdaexpr, *args, **kwargs):
...    '''luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)'''
...    nargs = len(args)
...    op = (kwargs.get('out',None),) + args
...    it = np.nditer(op, ['buffered','external_loop'],
...            [['writeonly','allocate','no_broadcast']] +
...                            [['readonly','nbo','aligned']]*nargs,
...            order=kwargs.get('order','K'),
...            casting=kwargs.get('casting','safe'),
...            buffersize=kwargs.get('buffersize',0))
...    while not it.finished:
...        it[0] = lamdaexpr(*it[1:])
...        it.iternext()
...    return it.operands[0]
 >>> a = np.arange(5)
>>> b = np.ones(5)
>>> luf(lambda i,j:i*i + j/2, a, b)
array([  0.5,   1.5,   4.5,   9.5,  16.5])
 If operand flags “writeonly” or “readwrite” are used the operands may be views into the original data with the WRITEBACKIFCOPY flag. In this case nditer must be used as a context manager or the nditer.close method must be called before using the result. The temporary data will be written back to the original data when the __exit__ function is called but not before: >>> a = np.arange(6, dtype='i4')[::-2]
>>> with np.nditer(a, [],
...        [['writeonly', 'updateifcopy']],
...        casting='unsafe',
...        op_dtypes=[np.dtype('f4')]) as i:
...    x = i.operands[0]
...    x[:] = [-1, -2, -3]
...    # a still unchanged here
>>> a, x
(array([-1, -2, -3], dtype=int32), array([-1., -2., -3.], dtype=float32))
 It is important to note that once the iterator is exited, dangling references (like x in the example) may or may not share data with the original data a. If writeback semantics were active, i.e. if x.base.flags.writebackifcopy is True, then exiting the iterator will sever the connection between x and a, writing to x will no longer write to a. If writeback semantics are not active, then x.data will still point at some part of a.data, and writing to one will affect the other. Context management and the close method appeared in version 1.15.0.  Attributes

dtypestuple of dtype(s)

The data types of the values provided in value. This may be different from the operand data types if buffering is enabled. Valid only before the iterator is closed.
finishedbool

Whether the iteration over the operands is finished or not.
has_delayed_bufallocbool

If True, the iterator was created with the delay_bufalloc flag, and no reset() function was called on it yet.
has_indexbool

If True, the iterator was created with either the c_index or the f_index flag, and the property index can be used to retrieve it.
has_multi_indexbool

If True, the iterator was created with the multi_index flag, and the property multi_index can be used to retrieve it.  index

When the c_index or f_index flag was used, this property provides access to the index. Raises a ValueError if accessed and has_index is False.
iterationneedsapibool

Whether iteration requires access to the Python API, for example if one of the operands is an object array.
iterindexint

An index which matches the order of iteration.
itersizeint

Size of the iterator.  itviews

Structured view(s) of operands in memory, matching the reordered and optimized iterator access pattern. Valid only before the iterator is closed.  multi_index

When the multi_index flag was used, this property provides access to the index. Raises a ValueError if accessed accessed and has_multi_index is False.
ndimint

The dimensions of the iterator.
nopint

The number of iterator operands.
operandstuple of operand(s)

operands[Slice]
shapetuple of ints

Shape tuple, the shape of the iterator.  value

Value of operands at current iteration. Normally, this is a tuple of array scalars, but if the flag external_loop is used, it is a tuple of one dimensional arrays.     Methods
close() Resolve all writeback semantics in writeable operands.
copy() Get a copy of the iterator in its current state.
debug_print() Print the current state of the nditer instance and debug info to stdout.
enable_external_loop() When the "external_loop" was not used during construction, but is desired, this modifies the iterator to behave as if the flag was specified.
iternext() Check whether iterations are left, and perform a single internal iteration without returning the result.
remove_axis(i, /) Removes axis i from the iterator.
remove_multi_index() When the "multi_index" flag was specified, this removes it, allowing the internal iteration structure to be optimized further.
reset() Reset the iterator to its initial state.


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

Numerical negative, element-wise.  Parameters

xarray_like or scalar

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

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

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

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

yndarray or scalar

Returned array or scalar: y = -x. This is a scalar if x is a scalar.     Examples >>> np.negative([1.,-1.])
array([-1.,  1.])
 The unary - operator can be used as a shorthand for np.negative on ndarrays. >>> x1 = np.array(([1., -1.]))
>>> -x1
array([-1.,  1.])


numpy.nested_iters   numpy.nested_iters(op, axes, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', buffersize=0)

Create nditers for use in nested loops Create a tuple of nditer objects which iterate in nested loops over different axes of the op argument. The first iterator is used in the outermost loop, the last in the innermost loop. Advancing one will change the subsequent iterators to point at its new element.  Parameters

opndarray or sequence of array_like

The array(s) to iterate over.
axeslist of list of int

Each item is used as an “op_axes” argument to an nditer  flags, op_flags, op_dtypes, order, casting, buffersize (optional)

See nditer parameters of the same name    Returns

iterstuple of nditer

An nditer for each item in axes, outermost first      See also  nditer
  Examples Basic usage. Note how y is the “flattened” version of [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified the first iter’s axes as [1] >>> a = np.arange(12).reshape(2, 3, 2)
>>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"])
>>> for x in i:
...      print(i.multi_index)
...      for y in j:
...          print('', j.multi_index, y)
(0,)
 (0, 0) 0
 (0, 1) 1
 (1, 0) 6
 (1, 1) 7
(1,)
 (0, 0) 2
 (0, 1) 3
 (1, 0) 8
 (1, 1) 9
(2,)
 (0, 0) 4
 (0, 1) 5
 (1, 0) 10
 (1, 1) 11


numpy.newaxis

A convenient alias for None, useful for indexing arrays. Examples >>> newaxis is None
True
>>> x = np.arange(3)
>>> x
array([0, 1, 2])
>>> x[:, newaxis]
array([[0],
[1],
[2]])
>>> x[:, newaxis, newaxis]
array([[[0]],
[[1]],
[[2]]])
>>> x[:, newaxis] * x
array([[0, 0, 0],
[0, 1, 2],
[0, 2, 4]])
 Outer product, same as outer(x, y): >>> y = np.arange(3, 6)
>>> x[:, newaxis] * y
array([[ 0,  0,  0],
[ 3,  4,  5],
[ 6,  8, 10]])
 x[newaxis, :] is equivalent to x[newaxis] and x[None]: >>> x[newaxis, :].shape
(1, 3)
>>> x[newaxis].shape
(1, 3)
>>> x[None].shape
(1, 3)
>>> x[:, newaxis].shape
(3, 1)


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

Return the next floating-point value after x1 towards x2, element-wise.  Parameters

x1array_like

Values to find the next representable value of.
x2array_like

The direction where to look for the next representable value of x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
outndarray, None, or tuple of ndarray and None, optional

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

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

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

outndarray or scalar

The next representable values of x1 in the direction of x2. This is a scalar if both x1 and x2 are scalars.     Examples >>> eps = np.finfo(np.float64).eps
>>> np.nextafter(1, 2) == eps + 1
True
>>> np.nextafter([1, 2], [2, 1]) == [eps + 1, 2 - eps]
array([ True,  True])


numpy.NINF

IEEE 754 floating point representation of negative infinity. Returns  yfloat

A floating point representation of negative infinity.   See Also 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 isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity is equivalent to positive infinity. Examples >>> np.NINF
-inf
>>> np.log(0)
-inf


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

Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The values in a are always tested and returned in row-major, C-style order. To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.  Note When called on a zero-d array or scalar, nonzero(a) is treated as nonzero(atleast_1d(a)).  Deprecated since version 1.17.0: Use atleast_1d explicitly if this behavior is deliberate.    Parameters

aarray_like

Input array.    Returns

tuple_of_arraystuple

Indices of elements that are non-zero.      See also  flatnonzero

Return indices that are non-zero in the flattened version of the input array.  ndarray.nonzero

Equivalent ndarray method.  count_nonzero

Counts the number of non-zero elements in the input array.    Notes While the nonzero values can be obtained with a[nonzero(a)], it is recommended to use x[x.astype(bool)] or x[x != 0] instead, which will correctly handle 0-d arrays. Examples >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]])
>>> x
array([[3, 0, 0],
       [0, 4, 0],
       [5, 6, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))
 >>> x[np.nonzero(x)]
array([3, 4, 5, 6])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
       [1, 1],
       [2, 0],
       [2, 1]])
 A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the condition a > 3 is a boolean array and since False is interpreted as 0, np.nonzero(a > 3) yields the indices of the a where the condition is true. >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a > 3
array([[False, False, False],
       [ True,  True,  True],
       [ True,  True,  True]])
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
 Using this result to index a is equivalent to using the mask directly: >>> a[np.nonzero(a > 3)]
array([4, 5, 6, 7, 8, 9])
>>> a[a > 3]  # prefer this spelling
array([4, 5, 6, 7, 8, 9])
 nonzero can also be called as a method of the array. >>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))


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

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

x1, x2array_like

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

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

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

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

outndarray or scalar

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

  Examples >>> np.not_equal([1.,2.], [1., 3.])
array([False,  True])
>>> np.not_equal([1, 2], [[1, 3],[1, 4]])
array([[False,  True],
       [False,  True]])
 The != operator can be used as a shorthand for np.not_equal on ndarrays. >>> a = np.array([1., 2.])
>>> b = np.array([1., 3.])
>>> a != b
array([False,  True])


class numpy.number[source]

Abstract base class of all numeric scalar types.


numpy.NZERO

IEEE 754 floating point representation of negative zero. Returns  yfloat

A floating point representation of negative zero.   See Also PZERO : Defines positive 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.  isfiniteShows which elements are finite - not one of

Not a Number, positive infinity and negative infinity.   Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Negative zero is considered to be a finite number. Examples >>> np.NZERO
-0.0
>>> np.PZERO
0.0
 >>> np.isfinite([np.NZERO])
array([ True])
>>> np.isnan([np.NZERO])
array([False])
>>> np.isinf([np.NZERO])
array([False])


numpy.obj2sctype   numpy.obj2sctype(rep, default=None)[source]

Return the scalar dtype or NumPy equivalent of Python type of an object.  Parameters

repany

The object of which the type is returned.
defaultany, optional

If given, this is returned for objects whose types can not be determined. If not given, None is returned for those objects.    Returns

dtypedtype or Python type

The data type of rep.      See also
sctype2char, issctype, issubsctype, issubdtype, maximum_sctype

  Examples >>> np.obj2sctype(np.int32)
<class 'numpy.int32'>
>>> np.obj2sctype(np.array([1., 2.]))
<class 'numpy.float64'>
>>> np.obj2sctype(np.array([1.j]))
<class 'numpy.complex128'>
 >>> np.obj2sctype(dict)
<class 'numpy.object_'>
>>> np.obj2sctype('string')
 >>> np.obj2sctype(1, default=list)
<class 'list'>


class numpy.object_[source]

Any Python object.  Character code
'O'


numpy.ogrid   numpy.ogrid = <numpy.lib.index_tricks.OGridClass object>

nd_grid instance which returns an open multi-dimensional “meshgrid”. An instance of numpy.lib.index_tricks.nd_grid which returns an open (i.e. not fleshed out) mesh-grid when indexed, so that only one dimension of each returned array is greater than 1. The dimension and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive. However, if the step length is a complex number (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value is inclusive.  Returns
 mesh-grid

ndarrays with only one dimension not equal to 1      See also  np.lib.index_tricks.nd_grid

class of ogrid and mgrid objects  mgrid

like ogrid but returns dense (or fleshed out) mesh grids  r_

array concatenator    Examples >>> from numpy import ogrid
>>> ogrid[-1:1:5j]
array([-1. , -0.5,  0. ,  0.5,  1. ])
>>> ogrid[0:5,0:5]
[array([[0],
        [1],
        [2],
        [3],
        [4]]), array([[0, 1, 2, 3, 4]])]


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

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

shapeint or sequence of ints

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

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

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

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

outndarray

Array of ones with the given shape, dtype, and order.      See also  ones_like

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

Return a new uninitialized array.  zeros

Return a new array setting values to zero.  full

Return a new array of given shape filled with value.    Examples >>> np.ones(5)
array([1., 1., 1., 1., 1.])
 >>> np.ones((5,), dtype=int)
array([1, 1, 1, 1, 1])
 >>> np.ones((2, 1))
array([[1.],
       [1.]])
 >>> s = (2,2)
>>> np.ones(s)
array([[1.,  1.],
       [1.,  1.]])


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

Return an array of ones with the same shape and type as a given array.  Parameters

aarray_like

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

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

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

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

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

outndarray

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

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

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

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

Return a new array setting values to one.    Examples >>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.ones_like(x)
array([[1, 1, 1],
       [1, 1, 1]])
 >>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.])
>>> np.ones_like(y)
array([1.,  1.,  1.])


numpy.outer   numpy.outer(a, b, out=None)[source]

Compute the outer product of two vectors. Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [1] is: [[a0*b0  a0*b1 ... a0*bN ]
 [a1*b0    .
 [ ...          .
 [aM*b0            aM*bN ]]
  Parameters

a(M,) array_like

First input vector. Input is flattened if not already 1-dimensional.
b(N,) array_like

Second input vector. Input is flattened if not already 1-dimensional.
out(M, N) ndarray, optional

A location where the result is stored  New in version 1.9.0.     Returns

out(M, N) ndarray

out[i, j] = a[i] * b[j]      See also  inner
einsum

einsum('i,j->ij', a.ravel(), b.ravel()) is the equivalent.  ufunc.outer

A generalization to dimensions other than 1D and other operations. np.multiply.outer(a.ravel(), b.ravel()) is the equivalent.  tensordot

np.tensordot(a.ravel(), b.ravel(), axes=((), ())) is the equivalent.    References  1
: G. H. Golub and C. F. Van Loan, Matrix Computations, 3rd ed., Baltimore, MD, Johns Hopkins University Press, 1996, pg. 8.   Examples Make a (very coarse) grid for computing a Mandelbrot set: >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
>>> rl
array([[-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.],
       [-2., -1.,  0.,  1.,  2.]])
>>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
>>> im
array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
       [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
       [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
       [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
       [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
>>> grid = rl + im
>>> grid
array([[-2.+2.j, -1.+2.j,  0.+2.j,  1.+2.j,  2.+2.j],
       [-2.+1.j, -1.+1.j,  0.+1.j,  1.+1.j,  2.+1.j],
       [-2.+0.j, -1.+0.j,  0.+0.j,  1.+0.j,  2.+0.j],
       [-2.-1.j, -1.-1.j,  0.-1.j,  1.-1.j,  2.-1.j],
       [-2.-2.j, -1.-2.j,  0.-2.j,  1.-2.j,  2.-2.j]])
 An example using a “vector” of letters: >>> x = np.array(['a', 'b', 'c'], dtype=object)
>>> np.outer(x, [1, 2, 3])
array([['a', 'aa', 'aaa'],
       ['b', 'bb', 'bbb'],
       ['c', 'cc', 'ccc']], dtype=object)


numpy.packbits   numpy.packbits(a, /, axis=None, bitorder='big')

Packs the elements of a binary-valued array into bits in a uint8 array. The result is padded to full bytes by inserting zero bits at the end.  Parameters

aarray_like

An array of integers or booleans whose elements should be packed to bits.
axisint, optional

The dimension over which bit-packing is done. None implies packing the flattened array.
bitorder{‘big’, ‘little’}, optional

The order of the input bits. ‘big’ will mimic bin(val), [0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011, ‘little’ will reverse the order so [1, 1, 0, 0, 0, 0, 0, 0] => 3. Defaults to ‘big’.  New in version 1.17.0.     Returns

packedndarray

Array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements. The shape of packed has the same number of dimensions as the input (unless axis is None, in which case the output is 1-D).      See also  unpackbits

Unpacks elements of a uint8 array into a binary-valued output array.    Examples >>> a = np.array([[[1,0,1],
...                [0,1,0]],
...               [[1,1,0],
...                [0,0,1]]])
>>> b = np.packbits(a, axis=-1)
>>> b
array([[[160],
        [ 64]],
       [[192],
        [ 32]]], dtype=uint8)
 Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, and 32 = 0010 0000.


numpy.pad   numpy.pad(array, pad_width, mode='constant', **kwargs)[source]

Pad an array.  Parameters

arrayarray_like of rank N

The array to pad.
pad_width{sequence, array_like, int}

Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.
modestr or function, optional

One of the following string values or a user supplied function.  ‘constant’ (default)

Pads with a constant value.  ‘edge’

Pads with the edge values of array.  ‘linear_ramp’

Pads with the linear ramp between end_value and the array edge value.  ‘maximum’

Pads with the maximum value of all or part of the vector along each axis.  ‘mean’

Pads with the mean value of all or part of the vector along each axis.  ‘median’

Pads with the median value of all or part of the vector along each axis.  ‘minimum’

Pads with the minimum value of all or part of the vector along each axis.  ‘reflect’

Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.  ‘symmetric’

Pads with the reflection of the vector mirrored along the edge of the array.  ‘wrap’

Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.  ‘empty’

Pads with undefined values.  New in version 1.17.   <function>

Padding function, see Notes.
stat_lengthsequence or int, optional

Used in ‘maximum’, ‘mean’, ‘median’, and ‘minimum’. Number of values at edge of each axis used to calculate the statistic value. ((before_1, after_1), … (before_N, after_N)) unique statistic lengths for each axis. ((before, after),) yields same before and after statistic lengths for each axis. (stat_length,) or int is a shortcut for before = after = statistic length for all axes. Default is None, to use the entire axis.
constant_valuessequence or scalar, optional

Used in ‘constant’. The values to set the padded values for each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad constants for each axis. ((before, after),) yields same before and after constants for each axis. (constant,) or constant is a shortcut for before = after = constant for all axes. Default is 0.
end_valuessequence or scalar, optional

Used in ‘linear_ramp’. The values used for the ending value of the linear_ramp and that will form the edge of the padded array. ((before_1, after_1), ... (before_N, after_N)) unique end values for each axis. ((before, after),) yields same before and after end values for each axis. (constant,) or constant is a shortcut for before = after = constant for all axes. Default is 0.
reflect_type{‘even’, ‘odd’}, optional

Used in ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extended part of the array is created by subtracting the reflected values from two times the edge value.    Returns

padndarray

Padded array of rank equal to array with shape increased according to pad_width.     Notes  New in version 1.7.0.  For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis. The padding function, if used, should modify a rank 1 array in-place. It has the following signature: padding_func(vector, iaxis_pad_width, iaxis, kwargs)
 where  vectorndarray

A rank 1 array already padded with zeros. Padded values are vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:].  iaxis_pad_widthtuple

A 2-tuple of ints, iaxis_pad_width[0] represents the number of values padded at the beginning of vector where iaxis_pad_width[1] represents the number of values padded at the end of vector.  iaxisint

The axis currently being calculated.  kwargsdict

Any keyword arguments the function requires.   Examples >>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6))
array([4, 4, 1, ..., 6, 6, 6])
 >>> np.pad(a, (2, 3), 'edge')
array([1, 1, 1, ..., 5, 5, 5])
 >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
array([ 5,  3,  1,  2,  3,  4,  5,  2, -1, -4])
 >>> np.pad(a, (2,), 'maximum')
array([5, 5, 1, 2, 3, 4, 5, 5, 5])
 >>> np.pad(a, (2,), 'mean')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
 >>> np.pad(a, (2,), 'median')
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
 >>> a = [[1, 2], [3, 4]]
>>> np.pad(a, ((3, 2), (2, 3)), 'minimum')
array([[1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1],
       [3, 3, 3, 4, 3, 3, 3],
       [1, 1, 1, 2, 1, 1, 1],
       [1, 1, 1, 2, 1, 1, 1]])
 >>> a = [1, 2, 3, 4, 5]
>>> np.pad(a, (2, 3), 'reflect')
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
 >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')
array([-1,  0,  1,  2,  3,  4,  5,  6,  7,  8])
 >>> np.pad(a, (2, 3), 'symmetric')
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
 >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
 >>> np.pad(a, (2, 3), 'wrap')
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
 >>> def pad_with(vector, pad_width, iaxis, kwargs):
...     pad_value = kwargs.get('padder', 10)
...     vector[:pad_width[0]] = pad_value
...     vector[-pad_width[1]:] = pad_value
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.pad(a, 2, pad_with)
array([[10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10,  0,  1,  2, 10, 10],
       [10, 10,  3,  4,  5, 10, 10],
       [10, 10, 10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10, 10, 10]])
>>> np.pad(a, 2, pad_with, padder=100)
array([[100, 100, 100, 100, 100, 100, 100],
       [100, 100, 100, 100, 100, 100, 100],
       [100, 100,   0,   1,   2, 100, 100],
       [100, 100,   3,   4,   5, 100, 100],
       [100, 100, 100, 100, 100, 100, 100],
       [100, 100, 100, 100, 100, 100, 100]])


numpy.partition   numpy.partition(a, kth, axis=- 1, kind='introselect', order=None)[source]

Return a partitioned copy of an array. Creates a copy of the array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.  New in version 1.8.0.   Parameters

aarray_like

Array to be sorted.
kthint or sequence of ints

Element index to partition by. The k-th value of the element will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all elements indexed by k-th of them into their sorted position at once.  Deprecated since version 1.22.0: Passing booleans as index is deprecated.
axisint or None, optional

Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
kind{‘introselect’}, optional

Selection algorithm. Default is ‘introselect’.
orderstr or list of str, optional

When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string. Not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.    Returns

partitioned_arrayndarray

Array of the same type and shape as a.      See also  ndarray.partition

Method to sort an array in-place.  argpartition

Indirect partition.  sort

Full sorting    Notes The various selection algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The available algorithms have the following properties:
kind speed worst case work space stable
‘introselect’ 1 O(n) 0 no   All the partition algorithms make temporary copies of the data when partitioning along any but the last axis. Consequently, partitioning along the last axis is faster and uses less space than partitioning along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Examples >>> a = np.array([3, 4, 2, 1])
>>> np.partition(a, 3)
array([2, 1, 3, 4])
 >>> np.partition(a, (1, 3))
array([1, 2, 3, 4])


numpy.percentile   numpy.percentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, interpolation=None)[source]

Compute the q-th percentile of the data along the specified axis. Returns the q-th percentile(s) of the array elements.  Parameters

aarray_like

Input array or object that can be converted to an array.
qarray_like of float

Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive.
axis{int, tuple of int, None}, optional

Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array.  Changed in version 1.9.0: A tuple of axes is supported
outndarray, optional

Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary.
overwrite_inputbool, optional

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

This parameter specifies the method to use for estimating the percentile. 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:  ‘inverted_cdf’ ‘averaged_inverted_cdf’ ‘closest_observation’ ‘interpolated_inverted_cdf’ ‘hazen’ ‘weibull’ ‘linear’ (default) ‘median_unbiased’ ‘normal_unbiased’  The first three methods are discontiuous. NumPy further defines the following discontinuous variations of the default ‘linear’ (7.) option:  ‘lower’ ‘higher’, ‘midpoint’ ‘nearest’   Changed in version 1.22.0: This argument was previously called “interpolation” and only offered the “linear” default and last four options.
keepdimsbool, optional

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array a.  New in version 1.9.0.
interpolationstr, optional

Deprecated name for the method keyword argument.  Deprecated since version 1.22.0.     Returns

percentilescalar or ndarray

If q is a single percentile and axis=None, then the result is a scalar. If multiple percentiles are given, first axis of the result corresponds to the percentiles. 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  mean
median

equivalent to percentile(..., 50)  nanpercentile
quantile

equivalent to percentile, except q in the range [0, 1].    Notes Given a vector V of length N, the q-th percentile of V is the value q/100 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 percentile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=50, the same as the minimum if q=0 and the same as the maximum if q=100. 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. Below, ‘q’ is the quantile value, ‘n’ is the sample size and alpha and beta are constants. The following formula gives an interpolation “i + g” of where the quantile would be in the sorted sample. With ‘i’ being the floor and ‘g’ the fractional part of the result.  \[i + g = (q - alpha) / ( n - alpha - beta + 1 )\] The different methods then work as follows  inverted_cdf:

method 1 of H&F [1]. This method gives discontinuous results: * if g > 0 ; then take j * if g = 0 ; then take i  averaged_inverted_cdf:

method 2 of H&F [1]. This method give discontinuous results: * if g > 0 ; then take j * if g = 0 ; then average between bounds  closest_observation:

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  interpolated_inverted_cdf:

method 4 of H&F [1]. This method give continuous results using: * alpha = 0 * beta = 1  hazen:

method 5 of H&F [1]. This method give continuous results using: * alpha = 1/2 * beta = 1/2  weibull:

method 6 of H&F [1]. This method give continuous results using: * alpha = 0 * beta = 0  linear:

method 7 of H&F [1]. This method give continuous results using: * alpha = 1 * beta = 1  median_unbiased:

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  normal_unbiased:

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  lower:

NumPy method kept for backwards compatibility. Takes i as the interpolation point.  higher:

NumPy method kept for backwards compatibility. Takes j as the interpolation point.  nearest:

NumPy method kept for backwards compatibility. Takes i or j, whichever is nearest.  midpoint:

NumPy method kept for backwards compatibility. Uses (i + j) / 2.   References
1(1,2,3,4,5,6,7,8,9,10)

R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages,” The American Statistician, 50(4), pp. 361-365, 1996   Examples >>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10,  7,  4],
       [ 3,  2,  1]])
>>> np.percentile(a, 50)
3.5
>>> np.percentile(a, 50, axis=0)
array([6.5, 4.5, 2.5])
>>> np.percentile(a, 50, axis=1)
array([7.,  2.])
>>> np.percentile(a, 50, axis=1, keepdims=True)
array([[7.],
       [2.]])
 >>> m = np.percentile(a, 50, axis=0)
>>> out = np.zeros_like(m)
>>> np.percentile(a, 50, axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
 >>> b = a.copy()
>>> np.percentile(b, 50, axis=1, overwrite_input=True)
array([7.,  2.])
>>> assert not np.all(a == b)
 The different methods can be visualized graphically: import matplotlib.pyplot as plt

a = np.arange(4)
p = np.linspace(0, 100, 6001)
ax = plt.gca()
lines = [
    ('linear', '-', 'C0'),
    ('inverted_cdf', ':', 'C1'),
    # Almost the same as `inverted_cdf`:
    ('averaged_inverted_cdf', '-.', 'C1'),
    ('closest_observation', ':', 'C2'),
    ('interpolated_inverted_cdf', '--', 'C1'),
    ('hazen', '--', 'C3'),
    ('weibull', '-.', 'C4'),
    ('median_unbiased', '--', 'C5'),
    ('normal_unbiased', '-.', 'C6'),
    ]
for method, style, color in lines:
    ax.plot(
        p, np.percentile(a, p, method=method),
        label=method, linestyle=style, color=color)
ax.set(
    title='Percentiles for different methods and data: ' + str(a),
    xlabel='Percentile',
    ylabel='Estimated percentile value',
    yticks=a)
ax.legend()
plt.show()


numpy.pi

pi = 3.1415926535897932384626433... References https://en.wikipedia.org/wiki/Pi


numpy.piecewise   numpy.piecewise(x, condlist, funclist, *args, **kw)[source]

Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.  Parameters

xndarray or scalar

The input domain.
condlistlist of bool arrays or bool scalars

Each boolean array corresponds to a function in funclist. Wherever condlist[i] is True, funclist[i](x) is used as the output value. Each boolean array in condlist selects a piece of x, and should therefore be of the same shape as x. The length of condlist must correspond to that of funclist. If one extra function is given, i.e. if len(funclist) == len(condlist) + 1, then that extra function is the default value, used wherever all conditions are false.
funclistlist of callables, f(x,*args,**kw), or scalars

Each function is evaluated over x wherever its corresponding condition is True. It should take a 1d array as input and give an 1d array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (lambda x: scalar) is assumed.
argstuple, optional

Any further arguments given to piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., 1, 'a'), then each function is called as f(x, 1, 'a').
kwdict, optional

Keyword arguments used in calling piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., alpha=1), then each function is called as f(x, alpha=1).    Returns

outndarray

The output is the same shape and type as x and is found by calling the functions in funclist on the appropriate portions of x, as defined by the boolean arrays in condlist. Portions not covered by any condition have a default value of 0.      See also
choose, select, where

  Notes This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. The result is:       |--
      |funclist[0](x[condlist[0]])
out = |funclist[1](x[condlist[1]])
      |...
      |funclist[n2](x[condlist[n2]])
      |--
 Examples Define the sigma function, which is -1 for x < 0 and +1 for x >= 0. >>> x = np.linspace(-2.5, 2.5, 6)
>>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
array([-1., -1., -1.,  1.,  1.,  1.])
 Define the absolute value, which is -x for x <0 and x for x >= 0. >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
array([2.5,  1.5,  0.5,  0.5,  1.5,  2.5])
 Apply the same function to a scalar value. >>> y = -2
>>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
array(2)


numpy.PINF

IEEE 754 floating point representation of (positive) infinity. Use inf because Inf, Infinity, PINF and infty are aliases for inf. For more details, see inf. See Also inf


numpy.place   numpy.place(arr, mask, vals)[source]

Change elements of an array based on conditional and input values. Similar to np.copyto(arr, vals, where=mask), the difference is that place uses the first N elements of vals, where N is the number of True values in mask, while copyto uses the elements where mask is True. Note that extract does the exact opposite of place.  Parameters

arrndarray

Array to put data into.
maskarray_like

Boolean mask array. Must have the same size as a.
vals1-D sequence

Values to put into a. Only the first N elements are used, where N is the number of True values in mask. If vals is smaller than N, it will be repeated, and if elements of a are to be masked, this sequence must be non-empty.      See also
copyto, put, take, extract

  Examples >>> arr = np.arange(6).reshape(2, 3)
>>> np.place(arr, arr>2, [44, 55])
>>> arr
array([[ 0,  1,  2],
       [44, 55, 44]])


numpy.poly   numpy.poly(seq_of_zeros)[source]

Find the coefficients of a polynomial with the given sequence of roots.  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.  Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned.  Parameters

seq_of_zerosarray_like, shape (N,) or (N, N)

A sequence of polynomial roots, or a square array or matrix object.    Returns

cndarray

1D array of polynomial coefficients from highest to lowest degree: c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N] where c[0] always equals 1.    Raises
 ValueError

If input is the wrong shape (the input must be a 1-D or square 2-D array).      See also  polyval

Compute polynomial values.  roots

Return the roots of a polynomial.  polyfit

Least squares polynomial fit.  poly1d

A one-dimensional polynomial class.    Notes Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. [1] In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use polyfit.) The characteristic polynomial, \(p_a(t)\), of an n-by-n matrix A is given by \(p_a(t) = \mathrm{det}(t\, \mathbf{I} - \mathbf{A})\), where I is the n-by-n identity matrix. [2] References  1
M. Sullivan and M. Sullivan, III, “Algebra and Trignometry, Enhanced With Graphing Utilities,” Prentice-Hall, pg. 318, 1996.  2
G. Strang, “Linear Algebra and Its Applications, 2nd Edition,” Academic Press, pg. 182, 1980.   Examples Given a sequence of a polynomial’s zeros: >>> np.poly((0, 0, 0)) # Multiple root example
array([1., 0., 0., 0.])
 The line above represents z**3 + 0*z**2 + 0*z + 0. >>> np.poly((-1./2, 0, 1./2))
array([ 1.  ,  0.  , -0.25,  0.  ])
 The line above represents z**3 - z/4 >>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0]))
array([ 1.        , -0.77086955,  0.08618131,  0.        ]) # random
 Given a square array object: >>> P = np.array([[0, 1./3], [-1./2, 0]])
>>> np.poly(P)
array([1.        , 0.        , 0.16666667])
 Note how in all cases the leading coefficient is always 1.


numpy.poly1d   class numpy.poly1d(c_or_r, r=False, variable=None)[source]

A one-dimensional polynomial class.  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.  A convenience class, used to encapsulate “natural” operations on polynomials so that said operations may take on their customary form in code (see Examples).  Parameters

c_or_rarray_like

The polynomial’s coefficients, in decreasing powers, or if the value of the second parameter is True, the polynomial’s roots (values where the polynomial evaluates to 0). For example, poly1d([1, 2, 3]) returns an object that represents \(x^2 + 2x + 3\), whereas poly1d([1, 2, 3], True) returns one that represents \((x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6\).
rbool, optional

If True, c_or_r specifies the polynomial’s roots; the default is False.
variablestr, optional

Changes the variable used when printing p from x to variable (see Examples).     Examples Construct the polynomial \(x^2 + 2x + 3\): >>> p = np.poly1d([1, 2, 3])
>>> print(np.poly1d(p))
   2
1 x + 2 x + 3
 Evaluate the polynomial at \(x = 0.5\): >>> p(0.5)
4.25
 Find the roots: >>> p.r
array([-1.+1.41421356j, -1.-1.41421356j])
>>> p(p.r)
array([ -4.44089210e-16+0.j,  -4.44089210e-16+0.j]) # may vary
 These numbers in the previous line represent (0, 0) to machine precision Show the coefficients: >>> p.c
array([1, 2, 3])
 Display the order (the leading zero-coefficients are removed): >>> p.order
2
 Show the coefficient of the k-th power in the polynomial (which is equivalent to p.c[-(i+1)]): >>> p[1]
2
 Polynomials can be added, subtracted, multiplied, and divided (returns quotient and remainder): >>> p * p
poly1d([ 1,  4, 10, 12,  9])
 >>> (p**3 + 4) / p
(poly1d([ 1.,  4., 10., 12.,  9.]), poly1d([4.]))
 asarray(p) gives the coefficient array, so polynomials can be used in all functions that accept arrays: >>> p**2 # square of polynomial
poly1d([ 1,  4, 10, 12,  9])
 >>> np.square(p) # square of individual coefficients
array([1, 4, 9])
 The variable used in the string representation of p can be modified, using the variable parameter: >>> p = np.poly1d([1,2,3], variable='z')
>>> print(p)
   2
1 z + 2 z + 3
 Construct a polynomial from its roots: >>> np.poly1d([1, 2], True)
poly1d([ 1., -3.,  2.])
 This is the same polynomial as obtained by: >>> np.poly1d([1, -1]) * np.poly1d([1, -2])
poly1d([ 1, -3,  2])
  Attributes
 c

The polynomial coefficients  coef

The polynomial coefficients  coefficients

The polynomial coefficients  coeffs

The polynomial coefficients  o

The order or degree of the polynomial  order

The order or degree of the polynomial  r

The roots of the polynomial, where self(x) == 0  roots

The roots of the polynomial, where self(x) == 0  variable

The name of the polynomial variable     Methods
__call__(val) Call self as a function.
deriv([m]) Return a derivative of this polynomial.
integ([m, k]) Return an antiderivative (indefinite integral) of this polynomial.


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

Find the sum 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.  Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.  Parameters

a1, a2array_like or poly1d object

Input polynomials.    Returns

outndarray or poly1d object

The sum of the inputs. If either input is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree.      See also  poly1d

A one-dimensional polynomial class.
poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval

  Examples >>> np.polyadd([1, 2], [9, 5, 4])
array([9, 6, 6])
 Using poly1d objects: >>> p1 = np.poly1d([1, 2])
>>> p2 = np.poly1d([9, 5, 4])
>>> print(p1)
1 x + 2
>>> print(p2)
   2
9 x + 5 x + 4
>>> print(np.polyadd(p1, p2))
   2
9 x + 6 x + 6


numpy.polyder   numpy.polyder(p, m=1)[source]

Return the derivative of the specified order of a polynomial.  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.   Parameters

ppoly1d or sequence

Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see poly1d.
mint, optional

Order of differentiation (default: 1)    Returns

derpoly1d

A new polynomial representing the derivative.      See also  polyint

Anti-derivative of a polynomial.  poly1d

Class for one-dimensional polynomials.    Examples The derivative of the polynomial \(x^3 + x^2 + x^1 + 1\) is: >>> p = np.poly1d([1,1,1,1])
>>> p2 = np.polyder(p)
>>> p2
poly1d([3, 2, 1])
 which evaluates to: >>> p2(2.)
17.0
 We can verify this, approximating the derivative with (f(x + h) - f(x))/h: >>> (p(2. + 0.001) - p(2.)) / 0.001
17.007000999997857
 The fourth-order derivative of a 3rd-order polynomial is zero: >>> np.polyder(p, 2)
poly1d([6, 2])
>>> np.polyder(p, 3)
poly1d([6])
>>> np.polyder(p, 4)
poly1d([0])


numpy.polydiv   numpy.polydiv(u, v)[source]

Returns the quotient and remainder of polynomial division.  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 input arrays are the coefficients (including any coefficients equal to zero) of the “numerator” (dividend) and “denominator” (divisor) polynomials, respectively.  Parameters

uarray_like or poly1d

Dividend polynomial’s coefficients.
varray_like or poly1d

Divisor polynomial’s coefficients.    Returns

qndarray

Coefficients, including those equal to zero, of the quotient.
rndarray

Coefficients, including those equal to zero, of the remainder.      See also
poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub

polyval
  Notes Both u and v must be 0-d or 1-d (ndim = 0 or 1), but u.ndim need not equal v.ndim. In other words, all four possible combinations - u.ndim = v.ndim = 0, u.ndim = v.ndim = 1, u.ndim = 1, v.ndim = 0, and u.ndim = 0, v.ndim = 1 - work. Examples  \[\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25\] >>> x = np.array([3.0, 5.0, 2.0])
>>> y = np.array([2.0, 1.0])
>>> np.polydiv(x, y)
(array([1.5 , 1.75]), array([0.25]))


numpy.polyfit   numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)[source]

Least squares polynomial fit.  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.  Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error in the order deg, deg-1, … 0. The Polynomial.fit class method is recommended for new code as it is more stable numerically. See the documentation of the method for more information.  Parameters

xarray_like, shape (M,)

x-coordinates of the M sample points (x[i], y[i]).
yarray_like, shape (M,) or (M, K)

y-coordinates of the sample points. Several data sets of sample points sharing the same x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset per column.
degint

Degree of the fitting polynomial
rcondfloat, optional

Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is len(x)*eps, where eps is the relative precision of the float type, about 2e-16 in most cases.
fullbool, optional

Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned.
warray_like, shape (M,), optional

Weights. If not None, the weight w[i] applies to the unsquared residual y[i] - y_hat[i] at x[i]. Ideally the weights are chosen so that the errors of the products w[i]*y[i] all have the same variance. When using inverse-variance weighting, use w[i] = 1/sigma(y[i]). The default value is None.
covbool or str, optional

If given and not False, return not just the estimate but also its covariance matrix. By default, the covariance are scaled by chi2/dof, where dof = M - (deg + 1), i.e., the weights are presumed to be unreliable except in a relative sense and everything is scaled such that the reduced chi2 is unity. This scaling is omitted if cov='unscaled', as is relevant for the case that the weights are w = 1/sigma, with sigma known to be a reliable estimate of the uncertainty.    Returns

pndarray, shape (deg + 1,) or (deg + 1, K)

Polynomial coefficients, highest power first. If y was 2-D, the coefficients for k-th data set are in p[:,k].  residuals, rank, singular_values, rcond

These values are only returned if full == True  residuals – sum of squared residuals of the least squares fit
 rank – the effective rank of the scaled Vandermonde

coefficient matrix
 singular_values – singular values of the scaled Vandermonde

coefficient matrix    rcond – value of rcond.  For more details, see numpy.linalg.lstsq.
Vndarray, shape (M,M) or (M,M,K)

Present only if full == False and cov == True. The covariance matrix of the polynomial coefficient estimates. The diagonal of this matrix are the variance estimates for each coefficient. If y is a 2-D array, then the covariance matrix for the k-th data set are in V[:,:,k]    Warns
 RankWarning

The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if full == False. The warnings can be turned off by >>> import warnings
>>> warnings.simplefilter('ignore', np.RankWarning)
      See also  polyval

Compute polynomial values.  linalg.lstsq

Computes a least-squares fit.  scipy.interpolate.UnivariateSpline

Computes spline fits.    Notes The solution minimizes the squared error  \[E = \sum_{j=0}^k |p(x_j) - y_j|^2\] in the equations: x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
...
x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]
 The coefficient matrix of the coefficients p is a Vandermonde matrix. polyfit issues a RankWarning when the least-squares fit is badly conditioned. This implies that the best fit is not well-defined due to numerical error. The results may be improved by lowering the polynomial degree or by replacing x by x - x.mean(). The rcond parameter can also be set to a value smaller than its default, but the resulting fit may be spurious: including contributions from the small singular values can add numerical noise to the result. Note that fitting polynomial coefficients is inherently badly conditioned when the degree of the polynomial is large or the interval of sample points is badly centered. The quality of the fit should always be checked in these cases. When polynomial fits are not satisfactory, splines may be a good alternative. References  1
Wikipedia, “Curve fitting”, https://en.wikipedia.org/wiki/Curve_fitting  2
Wikipedia, “Polynomial interpolation”, https://en.wikipedia.org/wiki/Polynomial_interpolation   Examples >>> import warnings
>>> x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> z = np.polyfit(x, y, 3)
>>> z
array([ 0.08703704, -0.81349206,  1.69312169, -0.03968254]) # may vary
 It is convenient to use poly1d objects for dealing with polynomials: >>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179 # may vary
>>> p(3.5)
-0.34732142857143039 # may vary
>>> p(10)
22.579365079365115 # may vary
 High-order polynomials may oscillate wildly: >>> with warnings.catch_warnings():
...     warnings.simplefilter('ignore', np.RankWarning)
...     p30 = np.poly1d(np.polyfit(x, y, 30))
...
>>> p30(4)
-0.80000000000000204 # may vary
>>> p30(5)
-0.99999999999999445 # may vary
>>> p30(4.5)
-0.10547061179440398 # may vary
 Illustration: >>> import matplotlib.pyplot as plt
>>> xp = np.linspace(-2, 6, 100)
>>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
>>> plt.ylim(-2,2)
(-2, 2)
>>> plt.show()


numpy.polyint   numpy.polyint(p, m=1, k=None)[source]

Return an antiderivative (indefinite integral) of a polynomial.  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 returned order m antiderivative P of polynomial p satisfies \(\frac{d^m}{dx^m}P(x) = p(x)\) and is defined up to m - 1 integration constants k. The constants determine the low-order polynomial part  \[\frac{k_{m-1}}{0!} x^0 + \ldots + \frac{k_0}{(m-1)!}x^{m-1}\] of P so that \(P^{(j)}(0) = k_{m-j-1}\).  Parameters

parray_like or poly1d

Polynomial to integrate. A sequence is interpreted as polynomial coefficients, see poly1d.
mint, optional

Order of the antiderivative. (Default: 1)
klist of m scalars or scalar, optional

Integration constants. They are given in the order of integration: those corresponding to highest-order terms come first. If None (default), all constants are assumed to be zero. If m = 1, a single scalar can be given instead of a list.      See also  polyder

derivative of a polynomial  poly1d.integ

equivalent method    Examples The defining property of the antiderivative: >>> p = np.poly1d([1,1,1])
>>> P = np.polyint(p)
>>> P
 poly1d([ 0.33333333,  0.5       ,  1.        ,  0.        ]) # may vary
>>> np.polyder(P) == p
True
 The integration constants default to zero, but can be specified: >>> P = np.polyint(p, 3)
>>> P(0)
0.0
>>> np.polyder(P)(0)
0.0
>>> np.polyder(P, 2)(0)
0.0
>>> P = np.polyint(p, 3, k=[6,5,3])
>>> P
poly1d([ 0.01666667,  0.04166667,  0.16666667,  3. ,  5. ,  3. ]) # may vary
 Note that 3 = 6 / 2!, and that the constants are given in the order of integrations. Constant of the highest-order polynomial term comes first: >>> np.polyder(P, 2)(0)
6.0
>>> np.polyder(P, 1)(0)
5.0
>>> P(0)
3.0


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

Find the product 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.  Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.  Parameters

a1, a2array_like or poly1d object

Input polynomials.    Returns

outndarray or poly1d object

The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree.      See also  poly1d

A one-dimensional polynomial class.
poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval

convolve

Array convolution. Same output as polymul, but has parameter for overlap mode.    Examples >>> np.polymul([1, 2, 3], [9, 5, 1])
array([ 9, 23, 38, 17,  3])
 Using poly1d objects: >>> p1 = np.poly1d([1, 2, 3])
>>> p2 = np.poly1d([9, 5, 1])
>>> print(p1)
   2
1 x + 2 x + 3
>>> print(p2)
   2
9 x + 5 x + 1
>>> print(np.polymul(p1, p2))
   4      3      2
9 x + 23 x + 38 x + 17 x + 3


numpy.polynomial.chebyshev.Chebyshev   class numpy.polynomial.chebyshev.Chebyshev(coef, domain=None, window=None)[source]

A Chebyshev series class. The Chebyshev class provides the standard Python numerical methods ‘+’, ‘-’, ‘*’, ‘//’, ‘%’, ‘divmod’, ‘**’, and ‘()’ as well as the methods listed below.  Parameters

coefarray_like

Chebyshev coefficients in order of increasing degree, i.e., (1, 2, 3) gives 1*T_0(x) + 2*T_1(x) + 3*T_2(x).
domain(2,) array_like, optional

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(2,) array_like, optional

Window, see domain for its use. The default value is [-1, 1].  New in version 1.6.0.      Methods
__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.
interpolate(func, deg[, domain, args]) Interpolate a function at the Chebyshev points of the first kind.
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.